<?php
/*
	(c)ASTA Technology Group LLC 2003-2005.
	SOME COMMON FUNCTIONS ARE HERE
*/

define('OUTPUT_DIRECT', 0);
define('OUTPUT_HAWXY', 1);


function windirname($path) {
	$path = str_replace("\\", "/", $path);
	return dirname($path);
}

function hawxy_parse($data) {
  global $tag_stack;
  global $err;
  global $banner;
  global $img_conversion_enabled;
  global $skin;
  global $allow_skin_attribute;
	// START OF HAWXY MAIN PART
	require_once("hawxy.inc.php");
	
	// init stack to hold received XML tags
	$tag_stack = new HAX_tagstack();
	
	// init XML parsing stuff
	$xml_parser = xml_parser_create();
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");
	
	// create array with all lines of XML input
	$line_buffer = explode("\n", $data);
	
	if (!xml_parse($xml_parser, $data, true))
	{
	  // @fixme: some PHP installations throw a warning, when the parser has been
	  // free'ed, before parsing is done.
	  // We just hide the warning here as a poor workaround ...
	   
	  // parse error has occured
	
	  $line_of_fault = xml_get_current_line_number($xml_parser);
	
	  if (0 && $line_of_fault > 5)
	  {
	    // dump erroneous line only
	    error($err[2], $xml_parser, $line_of_fault);
	  }
	  else
	  {
	    // in case of remote server-sided script errors the erroneous line 
	    // number is not really helpful ==> dump whole input additionally
	    $dump = $line_buffer[$line_of_fault-1] . ($data);
	    error($err[10] . " " . $line_of_fault . ": " . $err[2] . ": " . $dump, $xml_parser);
	  }
	}
	xml_parser_free($xml_parser);
}

//TEMPLATE FUNCTIONS:
class template {
	var $template_content;
	var $template_path;
	var $is_already_output = false;
	var $title;
	var $main;
	var $head;
	var $metadesc;
	
	var $company_name;
	var $company_address1;
	var $company_address2;
	var $company_city;
	var $company_state;
	var $company_zip;
	var $company_phone;
	var $company_fax;
	var $company_email;
	
	var $site_name;
	
	var $table_tmp_td;
	var $table_tmp_tr;
	var $table_width;
	var $table_cols;
	var $table_colnum;
	var $table_text;
	var $table_url;
	var $table_add_td;
	var $language;
	var $skip_expires_check = false;
	
	function template($path = false) {
		global $link, $bots_list, $supplier, $webportal_time_diff,$webportal_enable_order_confirmation,$images_http_prefix, $images_https_prefix,$staticimages_http_prefix,$staticimages_https_prefix, $request_ssl, $root_path, $debug_skip_ssl_check, $session_lifetime, $languages, $language_default;
		if (is_null($path)) return;
		
		if (!$request_ssl && !$debug_skip_ssl_check) {
			$url = $root_path . "/" . format_index_url();
			$this->go302($url);
		}
		
		if (!$this->skip_expires_check && !$this->index_page && isset($_SESSION['heartbeat']) && (time()-intval(@$_SESSION['heartbeat']))>$session_lifetime) {
			//die($_SESSION['heartbeat'] . " now " . time());
			@session_destroy();
            $url =format_ultimateloginpage_url(false, true);
			$this->go302($url);
		}
		$_SESSION['heartbeat'] = time();
		
		
		if (isset($_GET['lang']) && isset($languages[$_GET['lang']])) $_SESSION['language'] = $_GET['lang'];
		if (isset($_POST['lang']) && isset($languages[$_POST['lang']])) $_SESSION['language'] = $_POST['lang'];
		$this->language = isset($_SESSION['language']) ? $_SESSION['language'] : $language_default;
		if ($request_ssl) $this->staticimages_http_prefix=$staticimages_https_prefix.$languages[$this->language]['static_path']; else $this->staticimages_http_prefix=$staticimages_http_prefix.$languages[$this->language]['static_path'];
		if ($request_ssl) $this->images_http_prefix = $images_https_prefix; else $this->images_http_prefix = $images_http_prefix;

		include_once "hawhaw.inc.php";
		$this->hawhaw = new HAW_deck();
		if ($this->hawhaw->ml==HAW_HTML && !detect_mobile_device()) {
			$templates_dir = $languages[$this->language]['templates_dir_html'];
			$this->output = OUTPUT_DIRECT;
			//echo "Output: HTML<BR>\n";
		} else {
			$templates_dir = $languages[$this->language]['templates_dir_hawxml'];
			//echo "Output: Mobile<BR>\n";
			$this->output = OUTPUT_HAWXY;
		}
		
		
		if (!$path) $path = $GLOBALS['default_template'];
		$path = $templates_dir . $path;
		$this->template_content = @file_get_contents($path);
		$this->template_path = $path;
		//ob_end_flush();
		ob_implicit_flush(0);
		//ob_start("my_buffer");
		//register_shutdown_function("my_buffer_end");
		
		/*
		//populating info used on all pages
		$details = new xml("als_get_company_info.cgi", "content=true");
		$details->extract_to_object($this);
		$details->extract_namespaces_to_object($this);
		*/
		
		//default URLs:
		$this->index_url = format_index_url();
		if (isset($_SESSION["cart"])) {
			$this->cart_url = format_cart_url();
			$this->checkout_url = format_checkout_url();
		}
		$this->index_url = format_index_url();
		$this->logingroup_url = format_logingroup_url();
		$this->login_url = format_login_url();
		$this->logout_url = format_logout_url();
		$this->pharmacies_url = format_pharmacies_url();
		$this->viewpharmacies_url = format_viewpharmacies_url();
		$this->viewnhpatients_url = format_viewnhpatients_url();
		$this->orderpharmacies_url = format_orderpharmacies_url();
		$this->cholesterol_url = format_cholesterol_url();
		$this->bloodpressure_url = format_bloodpressure_url();
		$this->vaccination_url = format_vaccination_url();
		$this->bloodsugar_url = format_bloodsugar_url();
     	$this->bookfinish_url = format_bookfinish_url();
   		$this->orderrefills_confirmation_url = ($webportal_enable_order_confirmation) ? format_orderrefills_confirmation_url() : format_orderrefills_url();
	    $this->orderrefills_url = format_orderrefills_url();
		/*$this->frm_cholesterol_url = format_cholesterol_url("add");

		
		$this->contact_url = format_contact_url();
		$this->specials_url = format_specials_url();
		$this->history_url = format_history_url();
        $this->visit_history_url = format_visit_history_url();   
		$this->faq_url = format_faq_url();
        $this->password_change_url =  format_password_change_request_url();
        $this->lost_password_url =  format_lost_password_url();
		*/
		if (isset($_SESSION["user_id"])) {
			$this->logged = TRUE;
			$this->username = $_SESSION["username"];
		}
		//echo "Snapshot=" . $_SESSION['snapshot_url'] . "<BR>\n";
		//print_r($_SESSION['cart']);
		

	}
	
		
	function populate_from_node(&$node, $prefix = "") {
		foreach($node as $var => $val) {
			if ($prefix) $var = $prefix . "_" . $var;
//			echo "${var}=$val<BR>";
			$this->$var = $val;
		}
	}
	
	function show() {
		global $st_time, $speed_tests;
		if ($this->is_already_output) return false;
		
		ob_end_clean();
		
		if ($speed_tests) echo "\nProcessing time: " . (getmicrotime()-$st_time) . " sec<br>\n";
		$time3 = getmicrotime();
		
		
		$this->template_content = $this->process_template($this->template_content);
		$this->template_content = $this->process_template($this->template_content);
		
		if ($speed_tests) echo "\nTemplate time: " . (getmicrotime()-$time3) . " sec<br>\n";
		
			//$st_time = time();
		if ($this->output == OUTPUT_HAWXY) {
			hawxy_parse($this->template_content);
		} else {
			echo $this->template_content;
		}
		
		
		flush();
		//echo "\nOutput time:" . (time()-$st_time);
		//if ($time) echo "\nSPEED: " . round(strlen($this->template_content) / $time / 1024) . " KB/sec<br>\n";
		$this->is_already_output = true;
		return true;
	}
	
	function go404($error = false) {
		global $menu_link_class, $top, $template;
		if ($this->is_already_output) return false;
		header("HTTP/1.1 404 Not Found");
		$template = new template("template_404.html");
		$template->error = "That page is no longer available on our system.";
		if ($error) $template->error = $error;
		$template->title = $template->title2 = "Page not found";
		//$this->category_path = "<a $menu_link_class href=\"http://$domain/\">$top</a>";
		$template->show();
		exit;
	}
	
	function go301($url) {
		global $menu_link_class, $top, $template;
		@ob_end_clean();
		$this->is_already_output = true;
		if (headers_sent()) {
			//@ob_end_flush();
			echo "<SCRIPT>location.href='$url';</SCRIPT>";
			@flush();
		} else {
			@header("HTTP/1.1 301 Moved Permanently");
			@header("Location: $url");
		}
		exit;
	}
	
	
	function go302($url) {
		global $menu_link_class, $top, $template;
		@ob_end_clean();
		$this->is_already_output = true;
		if (headers_sent()) {
			//@ob_end_flush();
			echo "<SCRIPT>location.href='$url';</SCRIPT>";
			@flush();
		} else {
			@header("HTTP/1.1 302 Moved Temporarily");
			@header("Location: $url");
		}
		exit;
	}
	
	function flush() {
		if ($this->is_already_output) return false;
		ob_end_clean();
		
		$split = preg_split("|\\\$flush|is", $this->template_content, 2);
		$this->template_content = $split[1];
		$first = $this->process_template($split[0]);
		$first = $this->process_template($first);
		
		
		echo $first;
		flush();
		ob_start("my_buffer");
	}
	
	function process_template($str) {
		
	//	if ($_GET['demodata']) $str = preg_replace("|<demodata>.*?</demodata>|is", "", $str);
		
		if (isset($_SERVER["CGIA"]))
		 $upload_dir=windirname($_SERVER["CGIA"]);
		else if (isset($_SERVER["ORIG_PATH_TRANSLATED"]))
		 $upload_dir=windirname($_SERVER["ORIG_PATH_TRANSLATED"]);
		else if (isset($_SERVER["ORIG_SCRIPT_FILENAME"]))
		 $upload_dir=windirname($_SERVER["ORIG_SCRIPT_FILENAME"]);
		else if (isset($_SERVER["PATH_TRANSLATED"]))
		 $upload_dir=windirname($_SERVER["PATH_TRANSLATED"]);
		else 
		 $upload_dir=windirname($_SERVER["SCRIPT_FILENAME"]); 
		  
		//IFs
//		$str = preg_replace("|\{\{(!)?\\$([a-zA-Z][a-zA-Z0-9_]*)\{(.*?)\}\}\}|ise", "($1\$this->$2) ? stripslashes('$3') : \"\"", $str);
        $str = preg_replace_callback('/\{\$\w+\{(.*?)\}\}/is' , function($matches) {
            $bracesTemp = $matches[0];
            $brace = str_replace($matches[1] , "" , $bracesTemp);
            $brace = str_replace("}" , "" , $brace);
            $brace = str_replace("{" , "" , $brace);
            $brace = str_replace("$" , "" , $brace);

            // echo "The bool val is" . " " . $GLOBALS[$brace] . "\n";
            
            if (isset($this->$brace)) {
            		if ($this->$brace) {
            			return $matches[1];
            		} else {
            			return "";
            		}
            }	else {
            	return "";
            }
            
        }, $str);


        $str = preg_replace_callback('/\{\!\$\w+\{(.*?)\}\}/is' , function($matches) {
            $bracesTemp = $matches[0];
            $brace = str_replace($matches[1] , "" , $bracesTemp);
            $brace = str_replace("}" , "" , $brace);
            $brace = str_replace("{" , "" , $brace);
            $brace = str_replace("$" , "" , $brace);
            $brace = str_replace("!" , "" , $brace);


            // echo "The bool val is" . " " . $GLOBALS[$brace] . "\n";
            // test
            //!($this->test)
            if (!($this->$brace)) {
              //  return "";
             return $matches[1];
            } else {
                //return $matches[1];
                return "";
            }

        }, $str);




//        $str = preg_replace("|\{\{(!)?\\$([a-zA-Z][a-zA-Z0-9_]*)\{(.*?)\}\}\}|ise", "($1\$this->$2) ? stripslashes('$3') : \"\"", $str);


//		$str = preg_replace("|\{(!)?\\$([a-zA-Z][a-zA-Z0-9_]*)\{(.*?)\}\}|ise", "($1\$this->$2) ? stripslashes('$3') : \"\"", $str);
		//includes
/*
		echo "PATH_TRANSLATED=" . $_SERVER["PATH_TRANSLATED"] ."<BR>";
		echo "dirname(PATH_TRANSLATED)=" . dirname($_SERVER["PATH_TRANSLATED"]) ."<BR>";
		echo "uploaddir=" . $upload_dir ."<BR>";
		echo "TEmplate path=" . windirname($this->template_path) . "<BR>";
		echo "hi="  . $upload_dir . "/" . windirname($this->template_path) . "<BR>";
		readfile($upload_dir . "/" . windirname($this->template_path) . "/header.html");exit;
*/		
//    	$str = preg_replace("|\[\[(.*?)\]\]|ie", "\$this->process_template(\$this->process_template(file_get_contents('" . $upload_dir . "/" . windirname($this->template_path) . "/$1')))", $str);
		//patterns

        $str = preg_replace_callback('/\[\[(.*?)\]\]/is' , function($matches) use ($upload_dir) {

          return  $this->process_template($this->process_template(file_get_contents( $upload_dir . "/" . windirname($this->template_path) . "/$matches[1]")));

        }, $str);


         $str = preg_replace("|<<.*?>>.*?<</.*?>>|is", "", $str);
		//variables
		//$str = preg_replace("|\\$([a-zA-Z][a-zA-Z0-9_]*)|e", "(isset(\$this->$1)) ? \$this->process_template(\$this->$1) : \$this->process_template(\$GLOBALS['$1'])", $str);

        $str = preg_replace_callback('/\$\w+/is' , function($matches)  {
            $matchProperty = str_replace('$' , '' , $matches[0]);
            if(isset($this->$matchProperty)) {
                return $this->$matchProperty;
            } else {
                return $GLOBALS[$matchProperty];
            }

//            return  $this->process_template($this->process_template(file_get_contents( $upload_dir . "/" . windirname($this->template_path) . "/$matches[0]")));

        }, $str);

//		$str = preg_replace("|\\$([a-zA-Z][a-zA-Z0-9_]*)|e", "(isset(\$this->$1)) ? \$this->$1 : \$GLOBALS['$1']", $str);
		//wordlets
		//$str = preg_replace("|\[\[([^\]]*)\]\]|e", "wordlet(\"$1\")", $str);
		
		
		return $str;
	}
	
	function kill() {
		ob_end_clean();
		$this->is_already_output = true;
		exit;
	}
	
	function pattern($pattern_name) {
		preg_match("|<<$pattern_name>>(.*?)<</$pattern_name>>|is", $this->template_content, $match);
 		if ($match[1]) {
			$match[1] = $this->process_template($match[1]);
			return $match[1];
		} else {
			//if (DEBUG_MODE) echo "<br>$pattern_name pattern not found<br>";
			return false;
		}
	} //function
}


function my_buffer($buf) {
global $template;
	$template->main .= $buf;
	return;
	//return "$buf";
}

function my_buffer_end() {
global $template;
	if (method_exists ($template, "show")) $template->show(); //PHP5 workaround
}


//NEW TABLE FORMATTING
function format_selection2(&$object, $override_width = false, $td_pattern = "td", $tr_pattern = "tr") {
global $column_num, $core_image_path;
	if ($object->table_colnum == 1) {
	   $object->table_tmp_td = "";
	}
	if ($override_width===false) $object->table_width = ceil(100/$object->table_cols) . "%"; else $object->table_width = $override_width;
	
	if (!$object->table_text) {
		$object->table_text = "&nbsp;";
		$object->table_url = false;
	}
	
	$object->table_tmp_td .= $object->pattern($td_pattern);
	
	if ($object->table_colnum == $object->table_cols) {
	   $object->table_tmp_tr .= $object->pattern($tr_pattern);
	   $object->table_colnum=1;
	} else {
	   $object->table_colnum++;
	}
}

function close_tr(&$object, $td_pattern = "td", $tr_pattern = "tr") {
	if ($object->table_colnum == 1) return true;
	$object->table_text = "&nbsp;";
	$object->table_url = false;
	while ($object->table_colnum < $object->table_cols) {
		$object->table_tmp_td .= $object->pattern($td_pattern);
		$object->table_colnum++;
	}
   $object->table_tmp_tr .= $object->pattern($tr_pattern);
   $object->table_colnum=1;
}


//AUTOMATIC TABLE FORMATTING (DEPRECATED!)
function open_table($text, $width = "600", $cellspacing = "0", $cellpadding = "0") {
global $column_num;
   $column_num = 1;
   $ret = "\t<TABLE cellSpacing=\"$cellspacing\" cellPadding=\"$cellpadding\" width=\"$width\" border=0>\n";
   if ($text) $ret .= "\t\t<TR>\n\t\t\t<TD colSpan=7 align=\"center\">\n\t\t\t\t<p class=\"heading\">$text</p></TD></TR>\n";
   return $ret;
}

function format_selection($object, $url = false,$linktext = false, $cols = 4, $add_td = "", $divider = true, $override_width = false) {
global $column_num, $core_image_path;
	return false; //deprecated
   if ($column_num == 1) {
      $text .= "<tr>\n";
   } else {
      if ($divider) $text .= "\t\t\t\t<td width=\"1\" style=\"width:1px;\" background=\"$core_image_path/bg2.gif\"><img src=\"$core_image_path/bg2.gif\" width=\"1\" height=\"1\" border=\"0\"></td>\n";
   }
   if ($override_width===false) $width = ceil(100/$cols) . "%"; else $width = $override_width;
   $text .= "\n\t\t\t\t<TD WIDTH=\"$width\" class=boldLink$add_td>";
   if (!$linktext) {
      $text .= "&nbsp;";
   } else {
      if (!$url) {
		$text .= $linktext;
	   } else {
		$text .= "<A class=boldLink href=\"$url\">".$linktext."</A>";
	   }
   }
   $text .= "</TD>\n";
   if ($column_num == $cols) {
      $text .= "</tr>\n";
      $column_num=1;
   } else {
      $column_num++;
   }
   return $text;
}

function close_table($cols = 4, $divider = true) {
global $column_num;
   if ($column_num > 1) {
      for ($ix=$column_num; $ix<($cols+1); $ix++) {
         $text .= format_selection("","&nbsp;", $cols, "", $divider);
      }
   }
   $text .= "</TABLE>";
   return $text;
}





function format_like($str) {
	$str = mysql_escape_string($str);
	$str = preg_replace("/[^a-zA-Z0-9\-]/", "%", $str);
	$str = preg_replace("/%{2,}/", "%", $str);
	return $str;
}


function miltoampm($hour) {  
    $ampm = ($hour >=12 && $hour <24) ? "PM" : "AM";  
    $newhour = ($hour % 12 === 0) ? 12 : $hour % 12;  
    return $newhour . substr($hour,2,3). ' ' . $ampm;  
}  

function build_date($y, $m, $d, $hr, $min) {
	if (strlen($y)!=4) $y = date("Y");
	$m = substr("00".$m, -2);
	if ($m<1 || $m>12) $m = date("m");
	$d = substr("00".$d, -2);
	if ($d<1 || $d>31) $d = date("d");
	$hr = intval($hr);
	if ($hr<0 || $hr>23) $hr = "10"; else $hr = substr("00$hr", -2);
	$min = intval($min);
	if ($min<0 || $min>59) $min = "00"; else $min = substr("00$min", -2);
	return "$y-$m-$d $hr:$min";
}

function search_highlight($str, $search, $before = "<b>", $after = "</b>") {
	$words = preg_split("/\W/", $search);
	if (is_array($words)) {
		foreach($words as $word) {
			$str = preg_replace("/" . preg_quote($word) . "/i", $before . "$0" . $after, $str);
		}
	}
	return $str;
}

function validate_email($email) {
	if ($email != '') {
		if (preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*?[a-z]+$/is', $email)) { 
			return true;
		}
	}
	return false;
}

function unhtmlspecialchars( $string )
{
  $string = str_replace ( '&amp;', '&', $string );
  $string = str_replace ( '&#039;', '\'', $string );
  $string = str_replace ( '&quot;', '"', $string );
  $string = str_replace ( '&lt;', '<', $string );
  $string = str_replace ( '&gt;', '>', $string );
  return $string;
}
function fetch_contents( $p_url )
{
	$site_url = $p_url;
	
	$ch = curl_init();
	$timeout = 5; // set to zero for no timeout
	curl_setopt ($ch, CURLOPT_URL, $site_url);
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
	
	
	$file_contents = curl_exec($ch);
	curl_close($ch);
	
	return $file_contents;
}
function wp_get_islandname( $p_id )
{
	switch( $p_id )
	{
        case 0:
            $island = "All Islands";
            break; 
		case 1:
			$island = "Big Island";
            //$island = "Hawaii";               
			break;
		case 3:
			$island = "Maui";
			break;
		case 6:
			$island = "Oahu";
			break;
		case 7:
			$island = "Kauai";
			break;
		case 2:
			$island = "Lanai";
			break;
		case 5:
			$island = "Molokai";
			break;
	}
	return $island;
}

function wp_timestamp($change ) {
 
$timestamp = time();
$date_time_array = getdate($timestamp);

$hours = $date_time_array['hours'];
$minutes = $date_time_array['minutes'];
$seconds = $date_time_array['seconds'];
$month = $date_time_array['mon'];
$day = $date_time_array['mday'];
$year = $date_time_array['year'];

// use mktime to recreate the unix timestamp
// adding 19 hours to $hours
$timestamp = mktime($hours + $change,$minutes,$seconds,$month,$day,$year);
return $timestamp;
}

function CheckError($results = false) 
{
 $error = false;
 if (isset($results->error)) {
   if ($error_data = array_pop($results->error))  {
    $error = $error_data->row[0]->row[0]->error;   
  }                 
 }          
 return $error;
}                    

function validatehack(array $checkitemarray)
{

$go=1;
foreach($checkitemarray as $item)
{
    if (strpos(strtoupper($item),"<IMG")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),"SRC=")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),"HTML")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),"HTM")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),"PHP")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),".PL")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),".JS")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),".ASP")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),".CFM")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),".CGI")!==false)
    {
      $go=0;  
    }
    if (strpos(strtoupper($item),".RSS")!==false)
    {
      $go=0;  
    }
    if (substr(trim($item),0,1)==';')
    {
     $go=0;   
    }
    if (substr(trim($item),-1)==';')
    {
     $go=0;   
    }
    
    if ($go==0) {
      break;  
    }
}
return $go;    
    
}


?>