Location: PHPKode > projects > Homeless Mangement Information System > hmis/createclients.php
<?php
//*Client Data System, Copyright (C) 2000, 2001, 2002 Tedd Kelleher.  This is free software, subject to the 
//*GNU GENERAL PUBLIC LICENSE, Version 2, June 1991 (in file named gpl.txt), which should accompany 
//*any distribution of this file.  Tedd Kelleher can be contacted at hide@address.com


//NOTE: THIS FILE IS NOW ONLY USED FOR "CREATE NEW CLIENTS"... REPORT.PHP HANDLES ALL OTHER CLIENT FORMS...  TODO: More clean up to do here!

$page_access_levels = ':40:';
//$page_profile = "View Client Information";

////Header for every page that finds the include directory, connects to db, authenticates user access 
include("initialize_pointer.php");
if(!include($include_root."authenticate.inc")){echo "No Authentication"; exit; };

include($include_root."Questions_into_array_class.inc");
include($include_root."questions_display.inc");
include($include_root."Questions_answers_validation_class.inc");
include($include_root."question_set_validation_function.inc");
include($include_root."questions_into_tags_function.inc");
include($include_root."head.inc");
include($include_root."template_parser.inc");
include($include_root."page_elements_display.inc");
include($include_root."client_id_class.inc");
include($include_root."client_report_class.inc");
include($include_root."insert_household_report_class.inc");
include($include_root."insert_client_report_class.inc");
include($include_root."client_profile_class.inc");
include($include_root.'client_lookup_class.inc');
include($include_root."reports_class.inc");
//include($include_root."report_date_questions_class.inc");
include($include_root."relationships_class.inc");
include($include_root."user_info_functions.inc");
//include($include_root."referrals_class.inc");
include($include_root."encryption_class.inc");
include($include_root."date_encrypted_functions.inc");
include($include_root."services_functions.inc");

convert_post_and_get_variable ('report_name');
convert_post_and_get_variable ('report_unit');
convert_post_and_get_variable ("new_report_client_id");
convert_post_and_get_variable ('edit_report_id');  //yes_following_page
$edit_report_id += 0;
convert_post_and_get_variable ('form_answer_added_client');
convert_post_and_get_variable ('empty_form');
//convert_post_and_get_variable ('ref_to_org_id');
//$ref_to_org_id += 0;
convert_post_and_get_variable ('following_page');
convert_post_and_get_variable ('ok_continue');
//$ok_continue = false; //used for testing
//echo "report type: ".$report_type."<br>";
//echo "form_submitted: ".$form_submitted."<br>";

//init tag values that can be empty
$tag_values['{CLIENTS IN VIEW}'] = ' ';
$tag_values["{CLIENT IDENTIFIER ENTRY TABLE}"] = ' ';
$tag_values['{MATCHING_CLIENTS}'] = ' ';
$tag_values["{FORM_END}"] = ' ';
//reset top message values
if ($empty_form == 'success_yes_another_empty_form')
{
	//do nada
}else{
   //reset values
   $message = ' ';
   $message_type = 'ok';
}

//hack hack fixme todo why do things go awry when on 305 resubmitting a form with empty_form set
//Todo: currently $empty_form is mislabled as it is used as if it were $dont_empty_form...
//if ($message=='Client Identifiers/Profile successfully entered.')
//	$empty_form = 'success_yes_another_empty_form';

//echo "edit rep:$edit_report_id";
//echo "emptyform:$empty_form";

	$report_type_profile = pull_report_type_profile( $report_name );
    //display_client_report( $report_type_profile, $empty_form, $edit_report_id );
	
    //If there is a "next page" request, pull the info on the page that follows, and send to that page instead,
    // unless the next = 'none' or we are editing a report
    if ($following_page && $report_type_profile["report_that_follows"] != "none" && !$edit_report_id) {
        $report_type_profile = pull_report_type_profile ($report_type_profile["report_that_follows"]);
    }
	
	display_client_id_entry_form( $report_type_profile, $empty_form, $ok_continue );
	//header ( 'Location: '.$system_directory.'report.php?report_name=client_profile&empty_form=yes' );


//Define the values for tags contained in the html template
$tag_values["{FORM_START}"] = form_start ($this_page);
$tag_values["{PAGE TITLE}"] = page_title_table();
$tag_values["{MENU}"] = menu();
$tag_values["{HEAD}"] = head ($page_title, $head_page_specific, $head_dynamic_style);
$tag_values["{FOOTER}"] = footer();
template_parser ($html_template, $tag_values);





/********************************************************************************************
 * Name: display_client_id_entry_form():
 * Description: Displays form and posts form if not empty. 
 *
 * Details and Notes:
 * 
 * @param: $report_type_profile - array - form profile.
 * @param: $empty_form - string - if set is empty form.
 * @return: Nothing returned
 * 
 * History: Edited 1/21/04 by Jeff.
 ********************************************************************************************/
function display_client_id_entry_form ($report_type_profile, $empty_form, $ok_continue=true)
{
    GLOBAL $form_answer, $tag_values, $page_id, $html_template, $form_submitted, $question_validation_error,
            $access_level, $client_info, $page_title, $instructions, $user_id, $org_id, $group_id, $message,
            $message_type, $just_adding_empty_client_id_entry_forms_so_no_errors_please;
	
    //Pull permissions for this report we are looking at
    $perms = per_group_report_type_id ( $user_id, $org_id, $report_type_profile['report_type_id'] );
    
    if ( $perms['create_rpt'] != 1 )
	{
        redirect ( 'You are not allowed to create this client identifier form' );
        exit;
    }
    
    $instructions = "Enter new client identifying and profile information below. ";
    $page_title = "New Client Identifier/Profile Entry";
    $page_id = $report_type_profile["report_type_id"]; 
	
    //Define how many client id subforms are displayed
    secondary_form_answer_validation ("Total Forms", "extra_client_id_forms", $form_answer["extra_client_id_forms"], "", "0-9",
     	"2", "", "30");
    secondary_form_answer_validation ("Total Forms", "extra_client_id_forms", $form_answer["extra_client_id_forms_value"], "", "0-9",
     	"2", "", "30");
		
	//if set and no error get user extra input client forms value
    if ($form_answer["extra_client_id_forms"] && !$question_validation_error["extra_client_id_forms"]) 
	{
         $number_of_client_id_forms = $form_answer["extra_client_id_forms"];
		 $just_adding_empty_client_id_entry_forms_so_no_errors_please = TRUE;  //this is a hack to prevent error display when just adding more forms...
    }
    elseif (!$empty_form && !$question_validation_error["extra_client_id_forms_value"]) 
	{    //else if not empty and no error on hidden value, get hidden extra client forms value
	     
         $number_of_client_id_forms = $form_answer["extra_client_id_forms_value"]; 
    }
    else //neither of above is set so only one form
	{
         $number_of_client_id_forms =  "1";
    }
    
    //Pull client profile questions
    //echo "Report_type is: ".$report_type_profile["report_type_id"]."<p>";
    $client_profile_questions = new Questions_into_array ( $report_type_profile['report_type_id'], 
	                                                       $access_level, 
														   $org_id, $group_id,
                                                           'display' );
    
	//Save a unmodified quesiton set version for insertion and...
    $whole_question_set_attributes = $client_profile_questions->questions;
	
    //Unset the questions that are part of the client identifier, but still need to be part of queries
	unset($client_profile_questions->questions['98']);  //status
    unset($client_profile_questions->questions['100']); //year born
    unset($client_profile_questions->questions['101']); //gender
    
    $id = new Client_id;
    
    for($i = 0; $i < $number_of_client_id_forms; $i++)
	{
        //Pull Client profile questions for subform, such as "ethnicity" 
        $id->pull_client_profile_questions ($i, $client_profile_questions->questions, $client_profile_questions->question_elements); 
        
        //Build on the array defining the client id subform
        $id->pull_client_id_entry_questions_array ($i);
    }
    
    if(!$empty_form)
	{
	    //Put into array for validation only the questions from subform where the first initial was filled out, so that totally empty forms are not marked with errors for being incomplete
	    $answered_questions = $id->client_identifier_form_validation_setup ($form_answer, $number_of_client_id_forms);
		$i = 0;
		
		//Ensure all client names submitted for search are cased just as they are entered into the database.
		//That is, first letter of first, middle, and last name are capetalized and rest is lowercase.  This
		//is done because search, queries are all case sensative on encrypted values.
		for($i = 0; $i < $number_of_client_id_forms; $i++)    
		{
			if (strlen($form_answer["name_first$i"])>0)
				$form_answer["name_first$i"] = ucfirst(strtolower(trim($form_answer["name_first$i"])));
			if (strlen($form_answer["name_middle$i"])>0)
				$form_answer["name_middle$i"] = ucfirst(strtolower(trim($form_answer["name_middle$i"])));
			if (strlen($form_answer["name_last$i"])>0)
				$form_answer["name_last$i"] = ucfirst(strtolower(trim($form_answer["name_last$i"])));
		}
		
	    //Validate the subform info for subforms with the first initial filled as, as defined above
	    $validation = new Questions_answers_validation($answered_questions, $id->question_elements, $form_answer);
	    $validation_client_profile = new Questions_answers_validation($id->answered_client_profile_questions, $id->question_elements_client_profile, $form_answer);
    }
	
    //If no errors, form not empty, and no new request for more forms then process new client input....
    if (!$question_validation_error && !$empty_form && !$form_answer['extra_client_id_forms'])
	{
		//First Lookup similiar clients to present to user for confirmation.  Currently only do this once, second post (i.e.
		//are you sure you want to) will post clients even if similiar clients exist.  Hence bypass if 'OK to continue' set.
		if (!$ok_continue)
		{
			//$id_quests = new Client_id;
			$id->pull_client_id_entry_questions_array ( '0', 'yes' );
		    $validated_iden_ans = new Questions_answers_validation ( $id->questions, $id->question_elements, $form_answer );
		    //display_client_lookup_entry_form ( $validated_iden_ans->vetted_form_answer );
		    $clup = new Client_lookup;
			
			$index_for_alt_searches = $number_of_client_id_forms;
			
			$i = 0;
			
			foreach($validated_iden_ans->vetted_value AS $key => $val)
			{
				//don't care about any key-value pair whose key does not include an index.
				//more importantly, keys with no digit foo the next few lines of code that track this 'index'
				if (!ereg ( '[0-9]', $key))
					continue;
				
				//this one string search allows us to use equivalence which is more efficient below instead of 4+ more string searches.
				if (strpos($key,strval($i)))
				{
					++$j;
				}else{
					++$i;
				}
				
				//if SSN set (i.e. SSN does not begin with #code), then use SSN as it's own search criteria
				if ($key=="ss_number$i" && $val[0]!='#')
				{
					$filtered_q["ss_number$index_for_alt_searches"] = $id->questions[$key];
					$filtered_q["ss_number$index_for_alt_searches"]['question_id'] = "ss_number$index_for_alt_searches";
					$filtered_a["ss_number$index_for_alt_searches"] = $val;
					/*$filtered_q["client_gender$index_for_alt_searches"] = $id->questions["client_gender$i"];
					$filtered_a["client_gender$index_for_alt_searches"] = $validated_iden_ans->vetted_value["client_gender$i"];*/
					$index_for_alt_searches++;
				}
				
				//if  set, use org_generated_client_id as its own search criteria
				if ($key=="org_generated_client_id$i" && strlen($val)>0)
				{
					$filtered_q["org_generated_client_id$index_for_alt_searches"] = $id->questions[$key];
					$filtered_q["org_generated_client_id$index_for_alt_searches"]['question_id'] = "org_generated_client_id$index_for_alt_searches";
					$filtered_a["org_generated_client_id$index_for_alt_searches"] = $val;
					/*$filtered_q["client_gender$index_for_alt_searches"] = $id->questions["client_gender$i"];
					$filtered_a["client_gender$index_for_alt_searches"] = $validated_iden_ans->vetted_value["client_gender$i"];*/
					$index_for_alt_searches++;
				}
				
				//first and last name combo is a good search criteria but last name and year born is better so...
				if ($key=="name_first$i" || $key=="name_last$i")
				{
					$filtered_a[$key] = $val;
					$filtered_q[$key] = $id->questions[$key];
				}
				
				//and the year is...
				if ($key=="client_year_born$i")
				{
					//birth year is better to use than first name so unset name_first if set
					unset($filtered_a["name_first$i"]);
					unset($filtered_q["name_first$i"]);
					$filtered_a[$key] = $val;
					$filtered_q[$key] = $id->questions[$key];
				}
			}
			
			if (is_array($filtered_q) && is_array($filtered_a))
			{
				$matching_clients_identifier_array = $clup->lookup_similiar_clients ( $filtered_q, $filtered_a );
		    	$_SESSION['matching_clients_identifier_arrayB'] = $matching_clients_identifier_array;
			    
				if (is_array($matching_clients_identifier_array) && count($matching_clients_identifier_array)>0)
					$tag_values['{MATCHING_CLIENTS}'] = display_client_identifiers_table ( $matching_clients_identifier_array, 'The following client(s) look similiar to the new client(s) below. ', 'nolinks', '', 2 ).'<br>';
			}
			
			//echo '<table border=1 bordercolor=green><tr><td>'.pretty_var_dump($filtered_q).'</td><td>'.pretty_var_dump($filtered_a).'</td><td>'.pretty_var_dump($matching_clients_identifier_array).'</td></tr></table>';		
		}
		
		//If no similiar clients on first attempt or if ok to continue set then INSERT new client data
		if ( !is_array($matching_clients_identifier_array) || $ok_continue)
		{
            //Put all the client id form info submitted into a session array called $client_info; 
            //also build client identifier, and check if they are already in the database.
            $id->set_client_info_session_variables ($validation->vetted_value);
            $id->set_client_info_session_variables_client_profile ($validation_client_profile->vetted_value);
            
            $insert_new_clients = new Client_id;
            $insert_new_clients->client_id_assign($org_id);
        
	        $insert_profile = new Client_profile;
	        $insert_profile->insert_client_profile_answers ($report_type_profile["report_type_id"], $client_info, $whole_question_set_attributes);
			
			//Decide what kind of report to send them to, a service report or a turnaway report
	        //direct_to_page ($report_type_profile["report_type_id"], "yes_empty_form", "yes_following_page");
			//$report_type_profile = pull_report_type_profile ($report_type_profile["report_that_follows"]);
			if ($report_type_profile['report_that_follows'] != 'none' && !$edit_rpt)
			{
	            $report_type_profile = pull_report_type_profile ($report_type_profile['report_that_follows']);
	        }
			
			//Recursive call to build new, empty form...
			display_client_id_entry_form( $report_type_profile, 'success_yes_another_empty_form', '');
	    }
    }
	
	//Todo: if we decide we want to bring up an empty form, code below must run after above post, which means $empty_form + $ok_continue must NOT be set.
	
    //Because of errors, or not coming from a submission of client ids, build the html client id entry tables
	if ($question_validation_error || !$empty_form || $form_answer['extra_client_id_forms'] || !$ok_continue)
	{
		if ($question_validation_error)
		{
			$message = 'Client Identifiers/Profile not submitted. Please correct the errors below.';
        	$message_type = 'error';
		}else{
			$display_edit_button = true;
		}
		
        //echo "In the else of client identifiers<p>".$message.'<br>';
        //$page_id = "client_identifier_entry";
        $page_id = $report_type_profile['report_type_id'];
		
        $html_template = 'client_identifier_entry.html';
        
        //$tag_values["{FORM_END}"] .= display_hidden_form_values("report_type", $report_type);
        
        $tag_values["{FORM_END}"] = display_hidden_form_values ('form_answer[extra_client_id_forms_value]', $number_of_client_id_forms);
        
        $tag_values["{FORM_END}"] .= display_hidden_form_values('report_name', $report_type_profile['report_type_id']);
        
        //echo "Num of subforms: ".$number_of_client_id_forms."<p>";
        
        //Build the html for the client id entry page
		
		//echo pretty_var_dump($validation_client_profile->vetted_form_answer);
		//echo pretty_var_dump($validation->vetted_form_answer);
        $tag_values["{CLIENT IDENTIFIER ENTRY TABLE}"] = $tag_values['{MATCHING_CLIENTS}'] . $id->assemble_client_id_entry_table ('client_identifier',
              $number_of_client_id_forms, $validation_client_profile->vetted_form_answer, $validation->vetted_form_answer);
		
		//overwrite any error message.  Todo: Need to go through and get consistant regarding when this message is built so don't have to keep overwriting it...
		if ($just_adding_empty_client_id_entry_forms_so_no_errors_please)
		{
			$message = 'The number of client entry forms available below has been adjusted.';
		    $message_type = 'ok';
		}
	    
        //if submitted again the 'add clients' will take...
		if (!$question_validation_error && !$empty_form && !$form_answer['extra_client_id_forms'] && is_array($matching_clients_identifier_array))
		{
			$message = 'Client Identifiers entered are similiar to clients already in the system. Ok to continue?';
        	$message_type = 'error';
			$tag_values["{FORM_END}"] .= display_hidden_form_values ('ok_continue','1');
			$tag_values["{FORM_END}"] .= form_end ('Yes, OK to Submit Form', 3);
		}
		else
		{
			$tag_values["{FORM_END}"] .= form_end ('Submit Form', 1);
			
			if ($display_edit_button && !$empty_form && !$just_adding_empty_client_id_entry_forms_so_no_errors_please)
			{
					$cli_prof = new Client_profile();
	    			$tag_values['{CLIENTS IN VIEW}'] = $cli_prof->display_client_profile_table ( $client_info, 'Clients added', 'client_add' );
					$tag_values['{CLIENTS IN VIEW}'] .= '<table border=0 width=100%><tr><td><br>'.add_more_clients_button().'</td></tr></table><br>';
			}
		}
    }
}



?>
Return current item: Homeless Mangement Information System