<?php

function createRandom($len) {    
$chars = "abcdefghijkmnopqrstuvwxyz023456789";    
srand((double)microtime()*1000000);    
$i = 0;    
$s = '' ;    
while ($i <= $len) {        
$num = rand() % 33;        
$tmp = substr($chars, $num, 1);        
$s = $s . $tmp;        
$i++;    }    
return $s;
}


function print_header($body_script='') {

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>

<!-- START: META DATA charset=iso-8859-1 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="language" content="en">
<meta name="author" content=" ">
<meta name="subject" content=" ">
<meta name="keywords" content=" ">
<meta name="datecreated" content=" ">
<meta name="datereviewed" content=" ">
<!-- END: META DATA -->

<title>Veterans Re-Entry Search Services</title>

<style type="text/css" media="screen,print">
    @import url(/va_files/2009/styles/va-user-styles.css);
    @import url(/va_files/2009/styles/vaSearch.css);
    @import url(/va_files/2009/styles/jkmegamenu.css);
    @import url(/va_files/2009/styles/va-styles.css);
</style>

<style type="text/css" media="screen">
	#prBanner { display:none; }
</style>

<style type="text/css" media="print">
	#prBanner { padding:0px; margin:0px; border:0px; position: relative; }
	#banner-wrapper { display:none; }
	#banner-area-menu { display:none; }
	#footer-area-links { display:none; }
</style>

<script type="text/javascript" src="/va_files/2009/scripts/global.js"></script>

<!-- START: SURVEY -->
<script type="text/javascript" src="/va_files/fsrscripts/triggerParams.js"></script>
<script type="text/javascript" src="/va_files/fsrscripts/stdLauncher.js"></script>
<script type="text/javascript">Poll();</script>
<!-- END: SURVEY -->
</head>

<body class="mainbody" <?=$body_script?>>
<div id="skiplink"> <a href="#content-wrapper">skip to page content</a> </div>

<!-- START: OUTER CONTAINER -->
<div class="bdywrpr">

	<!-- START: VA PRINT BANNER -->
	<img src="/va_files/2009/images/inter-header-banner-print.gif" id="prBanner" width="996" height="100" alt="United States Department of Veterans Affairs" title="United States Department of Veterans Affairs">
	<!-- END: VA PRINT BANNER -->

	<!-- START: VA BANNER AND SEARCH FORM -->
	<div id="banner-wrapper">
		<!-- START: VA BANNER -->
		<div id="banner-image">
			<a href="http://www.domain/" title="United States Department of Veterans Affairs"><img src="/va_files/2009/images/inter-header-banner-va-seal.gif" width="538" height="94" alt="United States Department of Veterans Affairs" title="United States Department of Veterans Affairs"></a>
		</div>
		<!-- END: VA BANNER -->

		<!-- START: SEARCH FORM -->
		<div id="banner-area-search">
			<div id="search-area">
				<form name="searchForm" id="searchForm" method="GET" action="http://www.index.domain/search/va/va_search.jsp" style="margin:0px; padding:0px;">
					<script language="javascript" src="/va_files/2009/scripts/vaSearch.js" type="text/javascript"></script>
					<input name="TT" type="hidden" id="TThidden" value="1">
					<!-- do not insert line breaks in the div tag below -->
					<div id="mainSearchForm"><label for="searchtxt" style="display:none">Enter your search text</label><input name="QT" type="text" id="searchtxt" size="5" title="Enter your search text" value=""><label for="searchbtn" style="display:none">Button to start search</label><input name="searchbtn" type="submit" id="searchbtn" title="Button to start search" value="Search"></div>
					<!-- do not insert line breaks in the div tag above -->
					<div id="moreLink">&raquo;&nbsp;<a href="http://www.index.domain/search/va/va_adv_search.jsp" style="color:#ffffff" title="Go to Advanced Search Page">Open Advanced Search</a></div>
				</form>
			</div>
		</div>
		<!-- END: SEARCH FORM -->
	</div>
	<!-- END: VA BANNER AND SEARCH FORM -->

	<!-- START: MEGA MENU -->
	<div id="banner-area-menu">
		<!-- START: GLOBAL MEGA MENU LINKS -->
		<script language="javascript" type="text/javascript">createMenu();</script>
		<noscript>
			<!-- START: NOSCRIPT FOR GLOBAL MEGA MENU LINKS -->
			<ul>
				<li><a href="http://www.domain/" title="main menu item Home">Home</a></li>
				<li><a href="http://www.domain/landing2_vetsrv.htm" title="main menu item Veteran Services">Veteran Services</a></li>
				<li><a href="http://www.domain/landing2_business.htm" title="main menu item Business">Business</a></li>
				<li><a href="http://www.domain/landing2_about.htm" title="main menu item About VA">About VA</a></li>
				<li><a href="http://www.domain/landing2_media_room.htm" title="main menu item Media Room">Media Room</a></li>
				<li><a href="http://www.domain/landing2_locations.htm" title="main menu item Locations">Locations</a></li>
				<li><a href="http://www.domain/landing2_contact.htm" title="main menu item Contact Us">Contact Us</a></li>
			</ul>
			<!-- END: NOSCRIPT FOR GLOBAL MEGA MENU LINKS -->
		</noscript>
		<!-- END: GLOBAL MEGA MENU LINKS -->

		<!-- START: LOCAL MEGA MENU (RELATED LINKS) -->

		<!-- END: LOCAL MEGA MENU (RELATED LINKS) -->
	</div>
	<!-- END: MEGA MENU -->

	<div id="content-wrapper">

		<!-- START: CONTENT -->
		<div id="content-area-template-B">
                    
                    
                    <table cellspacing="2" cellpadding="5" width="960" border="0">
<tbody>
<tr>
<td valign="top" align="left">

			<!-- START: PAGE CONTENT -->

<?php
}



function print_footer() {

?>
</td>
</tr>
</tbody>
</table>
<!-- END: PAGE CONTENT -->

	    </div>
		<!-- END: CONTENT -->

		<hr id="content-footer-divider">

		<!-- START: VA FOOTER -->
		<div id="footer-area">
			<p id="footer-area-links">
				<a href="http://www.domain/" title="VA Home">VA Home</a>&nbsp;|&nbsp;
				<a href="http://www.domain/privacy/" title="Privacy Policy">Privacy Policy</a>&nbsp;|&nbsp;
				<a href="http://www.foia.domain/" title="FOIA">FOIA</a>&nbsp;|&nbsp;
				<a href="http://www.domain/webpolicylinks.asp" title="Web Policies">Web Policies</a>&nbsp;|&nbsp;
				<a href="http://www.domain/orm/NOFEAR_Select.asp" title="No FEAR Act Data">No FEAR Act Data</a>&nbsp;|&nbsp;
				<a href="http://www.domain/general/site_map.htm" title="Site Index">Site Index</a>&nbsp;|&nbsp;
				<a href="http://www.domain/ext_redirect.asp?url=http://www.usa.gov/&amp;type=1" title="USA.gov">USA.gov</a>&nbsp;|&nbsp;
				<a href="http://www.domain/ext_redirect.asp?url=http://www.whitehouse.gov/&amp;type=1" title="White House">White House</a>&nbsp;|&nbsp;
				<a href="http://www.domain/ext_redirect.asp?url=http://www.nationalresourcedirectory.gov/&amp;type=1" title="National Resource Directory">National Resource Directory</a>&nbsp;|&nbsp;
				<a href="http://www.domain/oig/" title="Inspector General">Inspector General</a>
			</p>
			<p id="footer-address">U.S. Department of Veterans Affairs - 810 Vermont Avenue, NW - Washington, DC 20420</p>
		</div>
		<!-- END: VA FOOTER -->

		<p id="footer-review">Reviewed/Updated Date: <!-- START: LAST MOD DATE -->September 1, 2010<!-- END: LAST MOD DATE --></p>

	</div>

</div>
<!-- END: OUTER CONTAINER -->

</body>
</html>

<?php

}

function scrub_white_list ($input, $option='default') {
	$black_list = NULL;
	
	switch($option) {
			
		case 'ALPHAONLY':
			$white_list = "/[^A-Za-z]+/";
			break;	
		
		case 'ALPHANUMERICONLY':
			$white_list = "/[^A-Za-z 0-9]+/";
			break;

		case 'BASIC':
			$white_list = "/[^A-Za-z0-9_ .\/\-]+/";
			//$white_list = "/[^A-Za-z0-9_ ,:?.()'%$\-*@\/!\#&=]+/";
			break;
			
		case 'DATA':
			//$white_list = "/[^A-Za-z0-9_ \r\n\t,.\-]+/";
			$white_list = "/[^A-Za-z0-9_ \r\n\t,.'\-]+/";
			break;
		
		case 'FILE':
			$white_list = "/[^A-Za-z0-9_ .\/\-]+/";
			//$white_list = "/[^A-Za-z0-9_ ,:?.()'%$\-*@\/!\#&=]+/";
			$black_list = '/ /';
			$input = preg_replace($black_list, '_', $input);
			
			break;
		
		case 'HTMLNOSCRIPT':
			$white_list = "/[^A-Za-z0-9_ \r\n\t,.:\/&;'\"@#!()=\[\]<>\-]+/";
			
			$black_list = "/(<.*(script|object|applet|embed|form|eval|event|iframe).*(script|object|applet|embed|form|eval|event|iframe).*>)/i";
			/*
			strPattern = "(<\s*(/)?(script|object|applet|embed|form|)\s*>)"   ' <  script xxx >
                        strPattern = strPattern & "|" & "(<.*>)"
                        strPattern = strPattern & "|" & "(&.{1,5};)"   ' &xxxx;
                        strPattern = strPattern & "|" & "eval\s*\("    ' eval  (
                        strPattern = strPattern & "|" & "(event\s*=)"  ' event  =
                    
                        'Now lets check for encoding
                        strPattern = Replace(strPattern, "<", "(<|%60|&lt;)")
                        strPattern = Replace(strPattern, ">", "(>|%62|&gt;)")
                        */
                        
			break;
		
		case 'INTERNALLINK':
			$white_list = "/[^A-Za-z0-9_.\/\-]+/";
			$black_list = "/(http|www|\.\.)/i";
			//$white_list = "/[^A-Za-z0-9_ ,:?.()'%$\-*@\/!\#&=]+/";
			break;
			
		case 'NUMBERONLY':
			$white_list = "/[^0-9]+/";
			break;
		
		case 'USER':
			$white_list = "/[^A-Za-z0-9_ .()\-@\+]+/";
			break;
			
			
		case 'default':	
		default:
			$white_list = "/[^A-Za-z0-9_ .]+/";
			break;
	}
		
	$count = 0;
	//$num_substr = 0;
	
	$output = preg_replace($white_list, '', $input, -1,$count);
	$_SESSION['count_substr'] = $count;
	
	if (!is_null($black_list)){
		$output = preg_replace($black_list, '', $output);
	}
	
	//$num_substr = 0 - $count;
	
	return $output;
	/*
	if( 0 < $count ){
		echo '<br>' . $count . '<br>';
		$output = substr($output, 0, $num_substr);	
		echo '<br>' . $output . '<br>';
		return $output;
	} else {
		return $output;
	}
	*/
}

function scrub ($field) {
$field = str_replace("~","",$field);
$field = str_replace("#","",$field);
$field = str_replace("$","",$field);
$field = str_replace("%","",$field);
$field = str_replace("^","",$field);
$field = str_replace("*","",$field);
$field = str_replace("<","",$field);
$field = str_replace(">","",$field);
$field = str_replace("{","",$field);
$field = str_replace("}","",$field);
$field = str_replace("|","",$field);
$field = str_replace(";","",$field);
$field = str_replace("'","",$field);
$field = str_replace("\"","",$field);
$field = str_replace("\0","",$field);
$field = stripslashes($field);

return $field;
}

function scrub_sql ($field, $length=0) {
//addslashes($field);
//$field = str_replace("#","",$field);
//$field = str_replace("$","",$field);
//$field = str_replace("%","",$field);
//$field = str_replace("*","",$field);
//$field = str_replace("{","",$field);
//$field = str_replace("}","",$field);
//$field = str_replace(";","",$field);
//$field = str_replace("\"","",$field);
//$field = str_replace("/","",$field);

$field = str_replace("'","''",$field);
$field = str_replace("\\","\\\\",$field);
$field = str_replace("\0","",$field);

//$field = str_replace("^","",$field);
//$field = str_replace("~","",$field);
//$field = str_replace("<","",$field);
//$field = str_replace(">","",$field);
//$field = str_replace("|","",$field);

//$field = stripslashes($field);
if ($length > 0) {
	$field = substr($field, 0, $length);
}

return $field;
}

function check_password($pwd) {
if (preg_match("/[a-z]/", $pwd) && preg_match("/[A-Z]/", $pwd) && preg_match("/[0-9]/", $pwd)) 
{
return true;
}

else {
return false;
}

}

function check_bad_char($field) {
$badCharacter = false;
$field = trim($field);
$charArray = preg_split('//', $field);

$badCharactersArray = array('#', '$', '%', '<', '>', '&', '!', '*', ' ');
for ($i = 0; $i < sizeof($badCharactersArray); $i++)
    {
        if (in_array ($badCharactersArray[$i], $charArray))
        {
            $badCharacter = true;
        }
    }

return $badCharacter;

}


function checklogin($userID, $target) {

if ($userID > 0) {
return true;
}
else {
header("Location: /login.php?target=$target");
return false;
}

}


function insert_app_data($uniqid) {
	//Enter data into the db
	
}

function print_ajax_header() {
?>
	<script type="text/javascript">
	function enter_app_data()
	{
		var result = 0;
		document.forms['thisform'].process_data.disabled=true;
		document.getElementById("proc_msg").innerHTML="Processing Data. Please wait.";
		animate('proc_msg', '#ff8000');

		var dataset_id = document.forms['thisform'].dataset_id.value;
		
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		} 
	
		xmlhttp.onreadystatechange = function () {
			
		  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			result = xmlhttp.responseText;
			document.getElementById("file_result").innerHTML=result;	//xmlhttp.responseText;
			animateloop('stop');
			document.getElementById("proc_msg").innerHTML="Processing Data Completed.";
		    }
		}
		
		//According to Mozilla's docs, you don't use onreadystatechange with synchronous requests. 
		//Use FireFox 4+ or check below
		//Even though the readystatechange event isn’t firing, the readyState property is actually getting updated. 

		xmlhttp.open("GET","app_ajax_handle.php?req=insert&dataset_id="+dataset_id,true);
		xmlhttp.send();
		
	 }	 
	</script>

<SCRIPT language="JavaScript"  type="text/javascript">

        var ie4 = false;
        if(document.all) {
                ie4 = true; 
        }       
        function setContent(name, value) {
                var d;  
                if (ie4) { 
                        d = document.all[name];
                } else {
                        d = document.getElementById(name);
                }       
                d.innerHTML = value;    
        }       

	function getContent(name) {
		var d;
                if (ie4) {
                        d = document.all[name];
                } else {
                        d = document.getElementById(name);
                }
                return d.innerHTML;
	}

        function setColor(name, value) {
                var d;  
                if (ie4) { 
                        d = document.all[name];
                } else {
                        d = document.getElementById(name);
                }
                d.style.color = value;  
        }

	function getColor(name) {
                var d;
                if (ie4) {
                        d = document.all[name];
                } else {
                        d = document.getElementById(name);
                }
                return d.style.color;
        }

        function animate(name, col, mode) {

		var value = getContent(name);
		if (value.indexOf('<span') >= 0) { return; }
		var length = 0;
		var str = '';
		var ch;
		var token = '';
		var htmltag = false;	
		for (i = 0; i < value.length; i++) {
			ch = value.substring(i, i+1);
			if (i < value.length - 1) { nextch = value.substring(i+1, i+2); } else { nextch = ' '; }
			token += ch;
			if (ch == '<' && '/aAbBpPhHiIoOuUlLtT'.indexOf(nextch) >= 0) { htmltag = true; }
			if (ch == '>' && htmltag) { htmltag = false; }
			if (!htmltag && ch.charCodeAt(0) > 30 && ch != ' ' && ch != '\n') {		
				str += '<span id="' + name + '_' + length + '">' + token + '</span>';
				token = '';
				length++;
			}
		}
		setContent(name, str);
		command = 'animateloop(\'' + name + '\', ' + length + ', 0, 1, \'' + col + '\')';
		setTimeout(command , 100);
                
        }

        function animateloop(name, length, ind, delta, col) {
        	if(name=="stop"){
        		exe = clearTimeout(exe);
        	} else {
			var next = ind + delta;
			if (next >= length) { delta = delta * -1; next = ind + delta; }
			if (next < 0) { delta = delta * -1; next = ind + delta; }
			setColor(name + '_' + ind, getColor(name + '_' + next));
			setColor(name + '_' + next, col);
			command = 'animateloop(\'' + name + '\', ' + length + ', ' + next + ', ' + delta + ', \'' + col + '\')';
			exe = setTimeout(command , 100);
                }
        }
</SCRIPT>
	
<?
}

function print_ajax_form($dataset_id) {

	$spacer = '&nbsp; &nbsp; &nbsp; &nbsp;';
?>
	<br><br>
	<form name='thisform' action='' method='post' id='thisform'>
		<div>

			<input name='dataset_id' id='dataset_id' type='hidden' value='<?=$dataset_id?>'/>
			
			<?=$spacer?><label for="process_data">Upload Data: </label><input name='process_data' type='button' value='Upload Data' onclick='enter_app_data()' /> <span id='proc_msg'></span><br><br>
			<span id='file_result'></span>
		</div>
	</form>


<?
}

function delete_app_files($dirname) { 

   return true; 
}

function inactivate_app_data($data_id) {
	global $db;
	$sql = 'BEGIN TRANSACTION
			UPDATE APP_Files SET status=\'INACTIVE\' WHERE file_id=\'' . $data_id . '\';
		
		COMMIT
		';

	$rs = $db->Execute($sql);
	$result = 'SUCCESS';
	
	return $result;
}

function activate_app_data($data_id) {
	global $db;
	$sql = 'BEGIN TRANSACTION
			UPDATE APP_Files SET status=\'ACTIVE\' WHERE file_id=\'' . $data_id . '\';
		
		COMMIT
		';	
	$rs = $db->Execute($sql);
	$result = 'SUCCESS';
	
	return $result;
}

function inactivate_all_previous_data($user_id, $program_id, $file_id) {

	global $db;
	$sql = 'SELECT id, file_id, user_id, program_id, dataset_id, file_type, status, upload_date
		FROM         APP_Files
		WHERE     (user_id = \'' . $user_id . '\') AND (program_id = \'' . $program_id . '\') AND (file_id <> \'' . $file_id . '\') AND (file_type = \'CSV\') AND (status = \'ACTIVE\') 
		ORDER BY upload_date DESC';	

	$rs = $db->Execute($sql);
	
	while (!$rs->EOF) { 

		$file_id = $rs->fields('file_id');
		inactivate_app_data($file_id);
		
		$rs->MoveNext();
	}
	
}

function audit_log($userID, $message) {
	global $db;
	$sql = "INSERT INTO tb_audit (user_id, event, event_date) VALUES ($userID, '$message', getdate())";
	$rs = $db->Execute($sql);
}

function toggle_app_onoff($onoff) {
	global $db;
	$sql = "UPDATE APP_Config SET value = '$onoff' WHERE name = 'user_login_switch'";
	$rs = $db->Execute($sql);
}

function capture_upload_report($userID,$file_upload_report) {
	global $db;

	$file_upload_report = htmlentities($file_upload_report, ENT_QUOTES);


	$sql = 'SET TEXTSIZE 2147483647 INSERT INTO APP_Upload_Reports (file_id, user_id, file_name, error_msg) VALUES (\''. $_SESSION['uniq_id'] . '\', ' . $userID . ', \'' . $_SESSION['zip_file'] . '\', \'' . $file_upload_report . '\')';
	$rs = $db->Execute($sql);
}

function insert_validated_data($zip_file, $user_id) {
		
	global $db;
	global $file_upload_path;
	
	$file_id = scrub_sql(scrub_white_list($_SESSION['uniq_id'], 'ALPHANUMERICONLY'), 15);

		$zip_file_name = scrub_white_list($_SESSION['zip_file'], 'INTERNALLINK');
		$num_data = scrub_sql(scrub_white_list($_SESSION['num_data'], 'NUMBERONLY'), 9);
		$spacer = '&nbsp; &nbsp; &nbsp; &nbsp;';
		
		if (!is_numeric($user_id)) {
			return 2;
			exit;
		}

		$tmp_work_dir = $file_upload_path . $file_id . '/';
		$tmp_work_unzip_dir = $tmp_work_dir . 'unzip/';
		
		$rs = $db->Execute("SELECT TOP 10 * FROM APP_Files ORDER BY ID ASC");
		$arr = $rs->GetArray();

		$zip_file_path = $tmp_work_unzip_dir . $zip_file_name;	

		if (is_readable($zip_file_path)) {
			$fp = fopen($zip_file_path, 'r');
		} else {
			return 9;

		}
		
		 $file_content = file_get_contents($zip_file_path) or die ("<br>File Get Contents failed.");

		$hex_file_content = scrub_sql(scrub_white_list(rtrim($file_content), 'DATA'));
		$safe_zip_file_name = scrub_sql($zip_file_name, 50);

		fclose($fp);

		$sql = 'Insert Into APP_Files (file_id, user_id, cs_id, dataset_id, name, uploaded_file, num_data, file_type) Values (';
		$sql .= "'$file_id', '$user_id', '" . $_SESSION['cs_id'] . "', 1,  '$safe_zip_file_name', '$hex_file_content', '$num_data', 'CSV')";

		$rs_put_contents = file_put_contents('/usr/local/vrss_sql/' .  $file_id, $sql);
		
		if (FALSE == $rs_put_contents){
			$result = '<br><br>' . $spacer . '<font color="red"><b>EVH File upload process Failed. Please contact administrator.</b></font>';
			$message = 'File upload failed ';
			audit_log($user_id, $message);
		} else {
			$result = '<br><br>' . $spacer . '<font color="navy"><b>The EVH upload was successful and the submitted file will be processed shortly.</b></font>';
			$message = 'File uploaded successfully ';
			audit_log($user_id, $message);
		}

		if ( isset($_SESSION['uniq_id']) ) { 

			unset($_SESSION['uniq_id']);
			unset($uniq_id);
		}
		
}

?>
