Location: PHPKode > projects > Homeless Mangement Information System > hmis/include/client_lookup_class.inc
<?php
//*Client Data System, Copyright (C) 2000, 2001, 2002, 2003 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: There are additional helper functions and classes below which are used in most places where Client_lookup class is used...

class Client_lookup
{
    var $sql_select_fields;
    var $sql_join;
    var $sql_join_count;
    var $sql_and;
    var $decode_and_check;
    var $matching_client_ids;
    var $not_matching_client_ids;
    var $query_specificity_count;
	var $run_match_status = FALSE;
	var $status_id_to_match;
    //var $en;
    
	function lookup_similiar_clients ( $quests, $vetted_ans )
	{
		$new_quests;
		$new_vetted_ans;
		
		$i = 0;
		$k = 0;
		
		foreach ($quests AS $qkey => $cur_q)
		{
			if (strpos($qkey,strval($i)))
			{
				$new_quests[$i][$qkey] = $cur_q;
			}
			else
			{
				ereg('[0-9]{1,5}',$qkey,$regs);
				$i = intval($regs[0]);
				$k = $i; //last index
				//echo "($i-$qkey) ";
				
				$new_quests[$i][$qkey] = $cur_q;
			}
		}
        
		$i = 0;
		foreach ($vetted_ans AS $akey => $cur_a)
		{
			if (strpos($akey,strval($i)))
			{
				$new_vetted_ans[$i][$akey] = $cur_a;
			}
			else
			{
				ereg('[0-9]{1,5}',$akey,$regs);
				$i = intval($regs[0]);
				$new_vetted_ans[$i][$akey] = $cur_a;
			}
		}
		
		//echo 'k='.$k;
		for ($i=0;$i<=$k;$i++)
		{
			//reset params
			$more_clients = null;
            
    	    $this->sql_select_fields = '';
    	    $this->sql_join = '';
    	    $this->sql_join_count = '';
    	    $this->sql_and = '';
   		    $this->decode_and_check = '';
    	    $this->matching_client_ids = '';
    	    $this->not_matching_client_ids = '';
    	    $this->query_specificity_count = 0;
		    $this->run_match_status = FALSE;
			
			//since the 'index' might skip around if search criteria exist for some new clients and not others then ensure we've got valid values to pass...
			if (array_key_exists($i,$new_quests))
				$more_clients = $this->lookup_client_using_identifiers ( $new_quests[$i], $new_vetted_ans[$i] );
			
			//echo '<table bordercolor=red border=1><tr><td>'.pretty_var_dump(array_keys($new_quests[$i])).'</td><td>'.pretty_var_dump($new_vetted_ans[$i]).'</td><td>'.count($more_clients).'</td></tr></table>';
			
			if (is_array($more_clients))
			{
				//$keys_all = array_push(array_keys($more_clients),array_keys($final_clients));
				if (!is_array($final_clients))
				{
					//echo "final became more<br>";
					$final_clients = $more_clients;
				}
				else
				{
					foreach($more_clients AS $cur_key => $cur_cli)
					{
						if ( !array_key_exists($cur_key,$final_clients) )
						{
							//echo "<br>push ".
							$final_clients[$cur_key] = $cur_cli;
							//array_push($final_clients, $cur_cli);
						}
					}
				}
			}
		}
		
		//echo pretty_var_dump($final_clients);
		
		//If no clients are matched or the matches are not accessible, sned signal of -1 for display function
        if ( !is_array ( $final_clients ) || count($final_clients)==0 )
		{
            $final_clients = -1;
        }
		else
		{
			//bugbug: $final_clients = array_unique ( $final_clients);
			//echo pretty_var_dump($keys_all);
		}
		
		return $final_clients;
	}



    function lookup_client_using_identifiers ( $quests, $vetted_ans )
	{
        global $org_id;
		
		//if (count($quests)>1)
		// return null;
		
        /*echo "<hr color=blue>vetted_ans:";
        echo pretty_var_dump ( $vetted_ans );
        echo "quests:";
		echo pretty_var_dump ( $quests );
        */
        //$this->en = new Encryption ();
        
        //Loop through the search values returned by the search form
        foreach ( $quests AS $cur_q )
		{
            //echo 'q:'.pretty_var_dump($cur_q['question_id']);
			//echo 'a:'.pretty_var_dump($vetted_ans[$cur_q['question_id']]['vetted_value']);
            if ( $vetted_ans[$cur_q['question_id']]['vetted_value'] || $cur_q['question_id']=='org_client_status0' )
			{
                //echo "IN:".$cur_q['question_id'] .' ';
                //If the query value contains a '?',....
                if ( preg_match ( "/\?/", $vetted_ans[$cur_q['question_id']] ) )
				{
                    //...search using the individual characters 'id_char[1-9]' fields
                    $this->add_partial_string_search_sql ( $cur_q, $vetted_ans[$cur_q['question_id']] );
                    //$this->decode_and_check
                }
                //..else search using the whole string
                else
				{
                    $this->add_whole_string_search_sql ( $cur_q, $vetted_ans[$cur_q['question_id']] );
                }
                
                //If it is a text type query, give them credit for specificity
                //echo pretty_var_dump ( $quests[$cur_q['question_id']]);
				//echo pretty_var_dump ( $vetted_ans[$cur_q['question_id']] );
                $q_type = $quests[$cur_q['question_id']]['question_type'];
                if ( $q_type == 'text' || $q_type == 'number' || $q_type == 'radio' || $q_type == 'dropdown')
				{
                    $holder = str_replace ( '?', '', $vetted_ans[$cur_q['question_id']] );
                    
                    $this->query_specificity_count = $this->query_specificity_count + strlen ( $holder );
                }
            }
        }
		
        //echo '<br>Specificty count is: '.$this->query_specificity_count.'<p>';
        //Check to see that there is specific enough a query, so it does not match all or most of the clients
        //NOTE: added succeeded_by delimiter to prevent hits on client lookup based on old values (i.e. decremented profiles)
        if ( $this->query_specificity_count > 2 )
        {
            $final_sql = "
            SELECT org_generated_client_ids0.client_id, org_generated_client_ids0.org_id, ".$this->sql_select_fields. "
             FROM ".$this->sql_join." WHERE org_generated_client_ids0.succeeded_by IS NULL AND ".$this->sql_and;
            //echo $final_sql."<p>";
            
            $client_result = run_query ( $final_sql, 'Pulling matching clients' );
            //echo "<p>";
            $returned_clients_count = num_rows ( $client_result );
        }
        elseif (!$this->run_match_status)
		{
		    //echo "<br>run_match_status=".$this->run_match_status;
            return -2;
        }
        //echo 'number of matching is: '. $returned_clients_count.'<p>';
        
		if (!isset($this->sql_join_count) && $this->run_match_status)
		{
			//echo "run just status search against is ".$this->status_id_to_match."<br>";
			
			//$final_sql = "
            //SELECT org_generated_client_ids0.client_id, org_generated_client_ids0.org_id, ".$this->sql_select_fields. "
            // FROM ".$this->sql_join." WHERE ".$this->sql_and;
			 
			$final_sql = "SELECT stat.status_id, ids.* FROM org_client_status stat INNER JOIN org_generated_client_ids ids ON stat.client_id = ids.client_id AND stat.org_id = ids.org_id WHERE stat.org_id = '".$org_id."' AND stat.status_id = '".$this->status_id_to_match."'";
			
            //echo $final_sql."<p>";
            
            $client_result = run_query ( $final_sql, 'Pulling matching clients' );
            //echo "<p>";
            $returned_clients_count = num_rows ( $client_result );
		}
		
        //Limit the number of matches
        if ( $returned_clients_count > 50 )
        {
            $returned_clients_count = 50;
        }
        
        //Loop through the matches
        for ( $i = 0; $i < $returned_clients_count; $i++ )
		{
            $t_array = fetch_array ( $client_result, 'Pulling unvetted lookup matches', $i );
            
            //$client_array[$t_array['client_id']] = $t_array;
            $client_array[$i] = $t_array;
        }
        
        //echo '<br>Vars in variable from initial SELECT: ';
        //echo count($client_array);
        //echo '<p>';
        
        //If there is an answer, (i.e., above $client_array returns an array.....       
        if ( is_array ( $client_array ) )
		{
            //...if a flag to decode and check returned results, do it
            if ( $this->decode_and_check )
			{
                $this->decode_and_check_long_search_strings ( $vetted_ans, $client_array );
                $matching_clients = $this->matching_client_ids;
            }
            else
			{
                //Convert to array client_id:org_id = info
                foreach ( $client_array AS $cur_cli )
				{
                    $matching_clients[$cur_cli['client_id']][$cur_cli['org_id']] = $cur_cli;
                    //echo 'Processing '.$cur_cli['client_id'].' - '.$cur_cli['org_id'].'<br/>'; 
                }
            }
            
            //If clients are retured by the above checking into an array, check to see if we have permission to access them
            if ( is_array ( $matching_clients ) )
			{
                $final_clients = $this->pull_accessible_client_identifier_reports ( $matching_clients );
            }
            
            //echo "Matches before status search:".count( $final_clients ); echo "<p>";
        }
        
        //If no clients are matched or the matches are not accessible, sned signal of -1 for display function
        if ( !is_array ( $final_clients ) )
		{
            $final_clients = -1;
        }
		
		//if join count was set then query may not yet be complete...
		if (isset($this->sql_join_count) && $this->run_match_status && isset($this->status_id_to_match))
		{
		    //echo "<p><b>status_id_to_match is:".$this->status_id_to_match."</b></p>";
			//We have access, now get status for matches AND if status was set in search further cull out those clients who do not match...
			$final_clients = $this->pull_accessible_client_status_report ( $final_clients, $this->run_match_status, $this->status_id_to_match);
		}
		
		//echo "Final matches: ".count( $final_clients ).' ';
		//var_dump(array_keys($final_clients));
		//echo "<hr color=blue>";
		//If no clients are matched or the matches are not accessible, sned signal of -1 for display function
        if ( !is_array ( $final_clients ) || count($final_clients)==0 )
		{
            $final_clients = -1;
        }
        
        return $final_clients;
    }





    function add_whole_string_search_sql ( $quest, $val )
	{
        //echo "In add whole string<p>";
        //echo "Val is: ".$val."<p>";
		//echo pretty_var_dump($quest);
		//echo "<p>";
        
		//status comes from a different table
		if ( substr( $quest['question_id'], 0, -1 ) == 'org_client_status' )
		{
		  //set globals used later for matching status
		  if ($val==11)
		  {
		  	$this->run_match_status=FALSE;
		  }
		  else
		  {
		  	$this->run_match_status=TRUE;
		  }
	      $this->status_id_to_match = $val;
		  return;
		}
		
        //Add a join.  If first call reset fields else begin building query...
        if ( $this->sql_join_count < 1 )
		{
            //Initialize the variables
            $this->sql_select_fields = '';
            $this->sql_join_count = '0';
            $this->sql_and = '';
            $this->sql_join .= " 
             org_generated_client_ids AS org_generated_client_ids".$this->sql_join_count;
        }
        else
		{
            $this->sql_select_fields .= ', ';
            
            $this->sql_join .= " 
            INNER JOIN org_generated_client_ids AS org_generated_client_ids".$this->sql_join_count."
                ON ( org_generated_client_ids0.client_id = org_generated_client_ids".$this->sql_join_count.".client_id )";
            //$this->sql_and .= ' AND';
            
            $this->sql_and .= "
            AND org_generated_client_ids0.org_id = org_generated_client_ids".$this->sql_join_count.".org_id AND";
        }
		
        //Add the fields we are selecting
        $this->sql_select_fields .= " org_generated_client_ids".$this->sql_join_count.".id_type AS id_type".$this->sql_join_count.', ';
        $this->sql_select_fields .= " org_generated_client_ids".$this->sql_join_count.".org_generated_client_id
          AS org_generated_client_id".$this->sql_join_count;
        
		//echo pretty_var_dump($quest);
		//echo "<p>";
        //Add an AND, first take off the '0' appended to question id
        $qid = substr ( $quest['question_id'], 0, -1 );
        
        //$this->sql_and .= " 
        //org_generated_client_ids".$this->sql_join_count.".org_generated_client_id LIKE '".$val."'
        //AND org_generated_client_ids".$this->sql_join_count.".id_type LIKE '".$qid."'";
        
        //$this->sql_and .= " 
        //id_type".$this->sql_join_count." LIKE '".$val."'
        //AND org_generated_client_id".$this->sql_join_count." LIKE '".$qid."'";
        
        $en = new Encryption ();
        $val = $en->encrypt_data ( $val );
        
        $this->sql_and .= "
        org_generated_client_ids".$this->sql_join_count.".org_generated_client_id LIKE '".$val."'
        AND org_generated_client_ids".$this->sql_join_count.".id_type LIKE '".$qid."'";
        
        //echo $this->sql_and."<p>";
    
        $this->sql_join_count++;
    }



    function add_partial_string_search_sql ( $quest, $val )
	{
        //echo "In partial string<p>";
        //echo "Val is: ".$val."<p>";
		//var_dump($quest);
		//echo "<p>";
        //Add a join
		
		//status comes from a different table
		if ( substr( $quest['question_id'], 0, -1 ) == 'org_client_status' )
		{
		  //set globals used later for matching status
		  if ($val==11) 
		  	$this->run_match_status=FALSE;
		  else
		  	$this->run_match_status=TRUE;
	      
		  $this->status_id_to_match = $val;
		  return;
		}
		
        if ( $this->sql_join_count < 1 )
		{
            //Initialize the variables
            $this->sql_join_count = '0';
            $this->sql_and = '';
            $this->sql_join .= " 
             org_generated_client_ids AS org_generated_client_ids".$this->sql_join_count;
        }
        else
		{
            $this->sql_select_fields .= ', '; 
            
            $this->sql_join .= " 
            INNER JOIN org_generated_client_ids AS org_generated_client_ids".$this->sql_join_count."
                ON ( org_generated_client_ids0.client_id = org_generated_client_ids".$this->sql_join_count.".client_id )";
            //$this->sql_and = ' AND';
            $this->sql_and .= "
            AND org_generated_client_ids0.org_id = org_generated_client_ids".$this->sql_join_count.".org_id AND"; 
        }
        
        //Add the fields we are selecting
        $this->sql_select_fields .= " org_generated_client_ids".$this->sql_join_count.".id_type AS id_type".$this->sql_join_count.', ';
        $this->sql_select_fields .= " org_generated_client_ids".$this->sql_join_count.".org_generated_client_id
          AS org_generated_client_id".$this->sql_join_count;
        
        //Make sure the questions types match
        $qid = substr ( $quest['question_id'], 0, -1 );
        $this->sql_and .= 
            " org_generated_client_ids".$this->sql_join_count.".id_type LIKE '".$qid."'";
        //$this->sql_and .= 
        //    " id_type".$this->sql_join_count." LIKE '".$qid."'";
        //$this->sql_and .= 
        //    " AND 1 = 1 ";
            

        ////Add an AND
        $len_of_query_term = strlen ( $val );
        //echo "Length is".$len_of_query_term.'<p>';
        //Loop through the search term
        
        $en = new Encryption ();
        
        for ( $i = 0; $i < $len_of_query_term; $i++ )
		{
            $cur_char = substr ( $val, $i, 1 );
            
            //echo "cahr on is".$i.'<p>';
            
            //Define the table field we are searching
            switch ( $i )
			{
                case 0:
                    $f_name = 'id_char_one';
                    break;
                case 1:
                    $f_name = 'id_char_two';
                    break;
                case 2:
                    $f_name = 'id_char_three';
                    break;
                case 3:
                    $f_name = 'id_char_four';
                    break;
                case 4:
                    $f_name = 'id_char_five';
                    break;
                case 5:
                    $f_name = 'id_char_six';
                    break;
                case 6:
                    $f_name = 'id_char_seven';
                    break;
                case 7:
                    $f_name = 'id_char_eight';
                    break;
                default:
                    //Note that we need to decode the string at the end to make sure it really matches
                    $this->decode_and_check[$qid] = $qid;
            }
            
            
            //Add to the actual SQL
            if ( !$this->decode_and_check[$qid] && $cur_char != '?' )
			{
             //echo 'f_name is'.$f_name.'<br>';
                $cur_char = $en->encrypt_data ( $cur_char );
                $this->sql_and .= 
                "  AND org_generated_client_ids".$this->sql_join_count.".".$f_name." LIKE '".$cur_char."'";
            }
        }
        $this->sql_join_count++;
    }



    function decode_and_check_long_search_strings ( $vetted_ans, $client_array )
	{
        //echo "Decoding long search<p>";
        //Loop through the arrays of clients and answers
        $en = new Encryption ();
        
        foreach ( $client_array AS $cur_client )
		{
            for ( $i = 0; $i < $this->sql_join_count; $i++ )
			{ 
                //Decode the answer
                //$cur_client
                //$decoded_answer = $cur_client['org_generated_client_id'.$i];
                $decoded_answer = $en->encrypt_data ( $cur_client['org_generated_client_id'.$i] );
                
                //echo 'Vars in varaible in decode and check long serach strings<br>';
                //var_dump ( $cur_client );
                //echo '<p>';
                
                //echo 'Current question id is: '.$cur_client['id_type'.$i].'<p/>';
                
                //Make preg_match syntax for the query
                //echo 'whole answer is: '.$vetted_ans[$cur_client['id_type'.$i].'0'].'<p/>';
                $reg_ex = str_replace ( '?', '.+', $vetted_ans[$cur_client['id_type'.$i].'0']  ); 
                //echo 'Regulate expresson is: '.$reg_ex.'<p/>';
                
                //Compare answer to query
                if ( preg_match ( '/\b'.$reg_ex.'\b/', $decoded_answer ) 
                     && !$this->not_matching_client_ids[$cur_client['client_id']][$cur_client['org_id']] )
				{
                    //There is a match, so note it by a two dimention array client_id:org_id = array
                    $this->matching_client_ids[$cur_client['client_id']][$cur_client['org_id']] = $cur_client;
                }
                else
				{
                    $this->not_matching_client_ids[$cur_client['client_id']][$cur_client['org_id']] = 'yes';
                    unset ( $this->matching_client_ids[$cur_client['client_id']][$cur_client['org_id']] );
                }
            }
            
        }
        
        //echo 'Matches after long string check<p>';
        //var_dump ( $this->matching_client_ids ); 
        //echo '<p>';
    }




    function pull_accessible_client_identifier_reports ( $client_ids_array )
	{
        GLOBAL $org_id, $user_id;
        $i = 0;
        
        $cl_prof = new Client_profile();
        
        //Loop through the identifiers matching the lookup query
        foreach ( $client_ids_array AS $cur_client_id => $cur_client )
        {
            //Find the client id
            foreach ( $cur_client AS $cur_org_id => $cur_clientB )
			{
                //echo 'Accessible check Current client id is: '.$cur_client_id.' - org is '.$cur_org_id.'<p/>';
                //var_dump ($cur_client);
                //echo '<p/>';
                
                //Pull out any matching client identifier reports
                $iden_report_array = $this->pull_related_identifier_report ( $cur_client_id, $cur_org_id );
                
                //Find out if we have permission to view report
                $perms = report_permissions_client ( $iden_report_array['client_rpt_id'] , $org_id, $user_id );
                if ( $perms['read_rpt'] == 1 )
				{
                    //Pull out all the org generated identifiers
                    //echo 'YES Accessible check Current client id is: '.$cur_client_id.' - org is '.$cur_org_id.'<p/>';
                    $org_gen_ids_array = $this->pull_related_org_identifiers ( $cur_client_id, $cur_org_id );
                    
                    $return_report[$cur_client_id][$cur_org_id] =  array_merge ( $iden_report_array , $org_gen_ids_array );
                    $i++;
                }
            
            }
        
        }
        
        //echo '<p>Here are reports we have permission for RAW<p>';
        //var_dump ( $org_gen_ids_array );
        //echo '<p>';
        /*
        echo 'Here are reports we have permission for<p>';
        var_dump ( $return_report );
        echo '<p>';
        */
        return $return_report;
    
    }



    function pull_accessible_client_status_report ( $client_ids_array, $match_status, $status_to_match )
	{
        GLOBAL $org_id, $user_id;
        
        $cl_prof = new Client_profile();
        
		//echo " Status to match ".$status_to_match;
		//echo "<br>pull_accessible_client_status_report (client_ids_array):<br>".pretty_var_dump($client_ids_array);
		
        //Loop through the identifiers matching the lookup query
		if (is_array($client_ids_array))
		{
	        foreach ( $client_ids_array AS $cur_client_id => $cur_client )
			{
	            //Find the client id
	            foreach ( $cur_client AS $cur_org_id => $cur_clientB )
				{ 
	                //echo '<p>Accessible check Current client id is: '.$cur_client_id.' - org is '.$cur_org_id.'</p>';
	                
					$a = array('org_client_status'=>'1');
					$client_ids_array[$cur_client_id][$cur_org_id] = array_merge($client_ids_array[$cur_client_id][$cur_org_id], $a);
	                
	                //Pull out any matching client status reports and delete client if status was set and does not match
					$status_id = $this->pull_status($cur_client_id, $cur_org_id);
					
					if ($match_status)
					{
						if ($status_id == $status_to_match)
						{
							$client_ids_array[$cur_client_id][$cur_org_id]['org_client_status'] = $status_id;
						}
						else
						{
						    //echo "<p>unsetting...".pretty_var_dump($client_ids_array)."</p>";
							unset($client_ids_array[$cur_client_id][$cur_org_id]);
							unset($client_ids_array[$cur_client_id]);
							//echo "<p>unset...".pretty_var_dump($client_ids_array)."</p>";
						}
					}
					else
					{
						$client_ids_array[$cur_client_id][$cur_org_id]['org_client_status'] = $status_id;
					}
	            }
	        }
		}
        
		//if the above status match wiped out all clients returned by first query than return null.
		if (!is_array($client_ids_array) || count($client_ids_array) == 0)
		{
			echo " returning null ";
			return NULL;
		}
		else
		{
        	return $client_ids_array;
		}
    }





	function pull_status($client_id, $org_id)
	{
        //Scaler, should only return one result/row...
		$sql = "
        SELECT org_client_status.status_id
            FROM org_client_status
            WHERE (org_client_status.client_id = '".$client_id."'
	        AND org_client_status.org_id = '".$org_id."')
		";
         
         $rpt_result = run_query_return_single_row( $sql, 'Pulling Client Status report id' );
         
		 if ( is_array($rpt_result) )
           return $rpt_result['status_id'];
		 else
		   return 99; //unknown, err
	}





    function pull_related_identifier_report ( $client_id, $org_id )   {
    
        $sql = "
        SELECT 
            DISTINCT(client_rpt_id), report_type, report_org_id
        FROM 
            client_rpt_profile, report_type_profile
         		WHERE report_type_profile.report_type_id LIKE client_rpt_profile.report_type
                    AND report_type_profile.report_on_unit LIKE 'client_identifier'
                    
					AND client_rpt_profile.client_id = '".$client_id."'
                    AND client_rpt_profile.report_org_id = '".$org_id."'
         			AND client_rpt_profile.succeeded_by IS NULL
                    
        "; 
         
         $rpt_result = run_query( $sql, 'Pulling Client Profile report numbers' );
         
         if ( num_rows ( $rpt_result ) > 0 )    {
            $rpt_array = fetch_array ( $rpt_result, 'Pulling arry of client rpt', 0 );
         }
         return $rpt_array;
        
    }



    /********************************************************************************************
     * Name: pull_related_org_identifiers: 
     * Description: Pulls client identifier fields, ssn, name, etc... given client id & org_id
     *
     * Details and Notes: Note that multiple ssn's, names, and other client identifier fields
     * may be returned if the client's identifiers have ever been edited.  For this reason it
     * is key that you use THE LAST value entered into the db (i.e. max org_gen_rowid)!!! The
     * easiest way to do this is ensure that succeeded_by IS NULL.
     * 
     * @param: $client_id
     * @param: $org_id
     * @param: $added_to_q_id ???
     * @return: html written to global $tag_values
     * 
     * History: Updated 3/9/03 by Jeff.
     ********************************************************************************************/
    function pull_related_org_identifiers ( $client_id, $org_id, $added_to_q_id = '' )
	{
        /*$sql = "
        SELECT 
            *
            FROM 
            org_generated_client_ids
         		WHERE 
                    org_generated_client_ids.client_id = '".$client_id."'
                    AND org_generated_client_ids.org_id = '".$org_id."'
                    AND succeeded_by IS NULL
                
        "; */
		
		$sql = "
			SELECT ids.*, stat.status_id
				FROM org_client_status stat 
				INNER JOIN 
					org_generated_client_ids ids
			    ON 
					stat.client_id = ids.client_id AND stat.org_id = ids.org_id
				WHERE
				ids.client_id = '".$client_id."' AND ids.org_id = '".$org_id."'
                AND ids.succeeded_by IS NULL
		";
		
        //echo "<p>pull_related_org_identifiers SQL is <br>".$sql."</p>";
        
        $array = run_query_return_array ( $sql, 'Pulling org generated client ids array' );
        
        $en = new Encryption ();
        
		//echo "<p>array:".pretty_var_dump($array)."</p>";
		
        if ( is_array ( $array ) )
		{
             foreach ( $array AS $cur_row )
			 {
                //echo '<p>ID type is: '.$cur_row['id_type'].' - id is: '.$cur_row['org_generated_client_id'].'<p>';
                $identifier = $en->decrypt_data ( $cur_row['org_generated_client_id'] );
                $rpt_array[$cur_row['id_type'].$added_to_q_id] = $identifier;
             }
			 //still on last row, grab status (which actually is an element of every row due)...
			 $array_element_for_status = array('org_client_status'.$added_to_q_id => $cur_row['status_id']);
			 $rpt_array = array_merge( $rpt_array, $array_element_for_status );
         }
         
		 // echo "<br>rpt_array:".pretty_var_dump($rpt_array)."<br>";
         return $rpt_array;
    }


    /********************************************************************************************
     * Name: pull_id_reports_matching_for_client: 
     * Description: Pulls client identifier fields, ssn, name, etc... given client id.
     *
     * Details and Notes: ensure that succeeded_by IS NULL.
     * 
     * @param: Several global params
     * @return: html written to global $tag_values
     * 
     * History: Updated 3/9/03 by Jeff.
     ********************************************************************************************/
    function pull_id_reports_matching_for_client ( $client_id )
	{
        /*$sql = "
        SELECT client_id, org_id, id_type, org_generated_client_id 
            FROM org_generated_client_ids
            WHERE client_id = '".$client_id."'
            AND succeeded_by IS NULL
        ";*/
		
		$sql = "
		SELECT ids.client_id, ids.org_id, ids.id_type, ids.org_generated_client_id, stat.status_id 
			FROM org_client_status stat 
			INNER JOIN org_generated_client_ids ids ON stat.client_id = ids.client_id AND stat.org_id = ids.org_id 
			WHERE ids.client_id = '".$client_id."'
            AND ids.succeeded_by IS NULL
		";
        
        $result_array = run_query_return_array ( $sql, 'Pulling matching ids' );
		
        $en = new Encryption ();
        
        //Convert to array client_id:org_id = info
        foreach ( $result_array AS $cur_cli )
        {
            $identifier = $en->decrypt_data ( $cur_cli['org_generated_client_id'] );
            $matching_clients[$cur_cli['client_id']][$cur_cli['org_id']][$cur_cli['id_type']] = $identifier;
			$array_element_for_status = array("org_client_status"=>$cur_cli['status_id']);
			$matching_clients[$cur_cli['client_id']][$cur_cli['org_id']] = 
				array_merge( $matching_clients[$cur_cli['client_id']][$cur_cli['org_id']], $array_element_for_status );
        }
        
        //Check to see if we have permission to access them
        if ( is_array ( $matching_clients ) )
        {
            $final_clients = $this->pull_accessible_client_identifier_reports ( $matching_clients );
        }
        
		//echo "HIHI:matching_clients:".pretty_var_dump ($matching_clients);
        return $matching_clients;
    }




}

///////////////////////////////////////////////////////Class
class Sharing_permissions_question
{
    var $questions;
    var $question_elements;
     
    function Sharing_permissions_question()
	{
        $this->questions["client_rpt_sharing_permission"] = array ("question_id" => "client_rpt_sharing_permission", "question_title" => "Client Info Shared?:", "question_type" => "radio", "question_field_size" => "", "question_range_bottom" => "", "question_range_top" => "", "question_display_order" => "103", "question_required" => "no", "question_default_value" => "no", "question_visible" => "yes", "question_ecma" => "");
        
        $this->question_elements["client_rpt_sharing_permission"]["yes"] = array ("question_element_id" => "element_client_rpt_sharing_permission_yes", "question_id" => "client_rpt_sharing_permission", "question_element_title" => "Yes", "question_element_value" => "yes");
		
		$this->question_elements["client_rpt_sharing_permission"]["no"] = array ("question_element_id" => "element_client_rpt_sharing_permission_no", "question_id" => "client_rpt_sharing_permission", "question_element_title" => "No", "question_element_value" => "no");
    }
}

///////////////////////////////////////////////////////The following Functions are not part of a class...


function display_client_lookup_entry_form ( $vetted_system_id_form_answer = '' )
{
	GLOBAL $page_id, $html_template, $tag_values, $button_label, $page_title, $instructions;
    
    $instructions .= "Look-up clients already in the system by entering some or all of the identifying information below. Use a \"?\" as a
    wildcard character. ";
    $page_id = 'client_lookup';
	$html_template = 'report_options.html'; //client_lookup.html';
    
	$id_system = new Client_id;
	$id_system->pull_client_id_entry_questions_array ( '0', 'yes' );
    
	//echo "vetted_sys_id_form_answ:".pretty_var_dump($vetted_system_id_form_answer);
	//echo "id_system:".pretty_var_dump($id_system);
	//Build the html for the client id entry page
	$tag_values["{CLIENT IDENTIFIER ENTRY TABLE}"] =
      $id_system->assemble_client_system_id_lookup_entry_table ( $vetted_system_id_form_answer, 'Look-up client(s) using the form below.', 'yes' );
    $tag_values['{MATCHING_CLIENTS}'] = ' ';
	//Build the html for the client id entry page
	
	$button_label = 'Return list of matching clients';
}



function display_client_identifiers_table ( $client_ids_array, $title, $no_links = '', $show_sysid = '', $tabstyle='')
{
	//GLOBAL $unix_date, $head_dynamic_style;
    GLOBAL  $unix_date, $message, $message_type; //$html_template, $page_id,
    
    //I think that sys id's should be displayed to super users only as this provides an important bit of info for narrowing down issues much faster.  ~jeff
    if ($_SESSION["super_user_idB"])
        $show_sysid = 'yes';
    
	//echo "<hr color=red>Client_ids_array:".pretty_var_dump($client_ids_array);
    
    if ($tabstyle)
    {
        $tableclass = "generictable2";
        $tableclasstop = "generictabletop2";
        $tableclasssub = "genericsubtop2";
        $tdclass = "smalltd";
    }
    else
    {
        $tableclass = "generictable";
        $tableclasstop = "generictabletop";
        $tableclasssub = "genericsubtop";
        $tdclass = "smalltd";
    }
    
    
    $final_html .= "<table class=\"".$tableclass."\">";
    
    if ( $client_ids_array == -1 )
	{
        $final_html .= "<tr><td class=\"".$tdclass."\">No clients match query</td></tr>";
        //echo "equlas -1";
    }
    elseif ( $client_ids_array == -2 )
	{
        $final_html .= "<tr><td class=\"".$tdclass."\">Need to enter at least three characters in search fields. </td></tr>";
        $message .= 'Need to enter at least three characters in search fields. ';
        $message_type .= 'error';
    }
    else
	{
        $final_html .= "<tr><td class=\"".$tableclasstop."\" colspan=\"9\">".$title."</td></tr></table>";
        $final_html .= "<table class=\"".$tableclass."\"><tr>";
		if ($show_sysid)
        	$final_html .= "<td class=\"".$tableclasssub."\">Sys. ID#</td>";
        $final_html .= "<td class=\"".$tableclasssub."\">Name</td>";
        $final_html .= "<td class=\"".$tableclasssub."\">Gender</td>";
        $final_html .= "<td class=\"".$tableclasssub."\">Birthday</td>";
        //Race broken
        //$final_html .= "<td class=\"".$tableclasssub."\">Race</td>";
        $final_html .= '<td class=\''.$tableclasssub.'\'>Status</td>';
        $final_html .= '<td class=\''.$tableclasssub.'\'>Org. Specific ID</td>';
        //$final_html .= '<td class=\''.$tableclasssub.'\'>ID Owner Org.</td>';
        $final_html .= '<td class=\''.$tableclasssub.'\'>Social Sec. #</td>';
		
        if ( !$no_links )
		{
            //$final_html .= '<td class=\''.$tableclasssub.'\'>Link</td>';
            $final_html .= '<td class=\''.$tableclasssub.'\'>Add to View</td>';
        }
        $final_html .= '</tr>';
        
        $color = array ( 'F79949', '6D87D4', 'FED105', 'FE6205', 'FE0561', '840561', '055BFF', '05D1FE', '05FE78', '7000FF' );
        $color_count = 0;
        
		//echo "<p><font color=red>";
        //pretty_var_dump($client_ids_array);
		//echo "</font></p>";
		
        //Cycle through the clients with client id as key    
	    foreach ( $client_ids_array AS $cli_id => $current_client )
		{
		    //echo "Profile is: ".$key. "=> ".$current_client."<br/>";
			//echo pretty_var_dump($current_client);
            $color_count++;
            if ( $color_count > 9 )
			{
                $color_count = 0;
            }
			
            //Cycle through the org id arrays for each client
            foreach ( $current_client AS $org_id => $cli_id_array )
			{
                //$sqly = "SELECT org_name FROM organizations WHERE org_id = '".$org_id."'";
			    //$org_name_result = run_query ( $sqly, 'Org Name Pull' );
			    //$report_org_name = fetch_result ( $org_name_result, 'Org name pull' );

                $sqly = "select distinct(client_rpt_answers.client_rpt_answer) as ethnicity from client_rpt_answers right join client_rpt_profile on client_rpt_profile.client_rpt_id = client_rpt_answers.client_rpt_id where client_rpt_answers.client_rpt_question_id = 102 and client_rpt_profile.client_id = ".$cli_id;
                $current_client_race = run_query_return_array ( $sqly, 'Race pull' );

                if ( is_array( $current_client_race ) ) {
                    $ww = 0;
                    $ethnicity_output = '';
                    foreach ( $current_client_race AS $one_ethnicity )   {
                        if ( $ww > 0 ) { $ethnicity_output .= '-'; }
                            $ww++;
                            $minus_underscore = str_replace ( '_', ' ', $one_ethnicity["ethnicity"] );
                            $minus_underscore = ucwords ( $minus_underscore );
                            $ethnicity_output .= str_replace ( ' ', '-', $minus_underscore );
                    }
                
                }
                
		        $final_html .= '<tr>';
                
				if ($show_sysid)
	                $final_html .= '<td class=\'".$tdclass."\' style=\'background-color: #'.$color[$color_count].'\'>'.$cli_id.'</td>';
                //properly display anonymous names or partial names
                if ($cli_id_array['name_last'])
                {
					$name = stripslashes(get_friendly_text($cli_id_array['name_last'])).', ';
				}
				else
				{
					$name = '?, ';
				}
				
				if ($cli_id_array['name_first'])
				{
					$name .= stripslashes(get_friendly_text($cli_id_array['name_first']));
				}
				else
				{
					$name .= '?';
				}
				if ($name=='?, ?') $name = 'Anonymous'; //todo: Question... Is it always the case that if both first and last name are null that this is an anonymous client?  Code assumes 'yes'.  Delete this comment if this is the case...  Another design question is if we should just leave anonymous data as ? as is done in birth day and month below...  i.e. stay consistant...
                $final_html .= "<td class=\"".$tdclass."\"><a class=\"smaller\" href=\"".$system_directory."client_overview.php?display_client_overview=".$cli_id."\">".$name."</a></td>";
                
                $final_html .= '<td class=\''.$tdclass.'\'>'.ucwords( str_replace( '_', ' ', stripslashes(get_friendly_text($cli_id_array['client_gender'])) ) ).'</td>';
                
                //Properly display partial or anonymous birth dates
				if ($cli_id_array['birth_month'])
				{
					$birthdate = stripslashes(get_friendly_text($cli_id_array['birth_month']));
				}
				else
				{
					$birthdate = '??';
				}
				if ($cli_id_array['birth_day'])
				{
					$birthdate .= '/'.stripslashes(get_friendly_text($cli_id_array['birth_day']));
				}
				else
				{
					$birthdate .= '/??';
				}
				if ($cli_id_array['client_year_born'])
				{
					$birthdate .= '/'.stripslashes(get_friendly_text($cli_id_array['client_year_born']));
				}
				else
				{
					$birthdate .= '/????';
				}
                $final_html .= '<td class=\'smalltd\'>'.$birthdate.'</td>';
                
                //$final_html .= '<td class=\'smalltd\'>'.$ethnicity_output.'</td>';
                
				$final_html .= '<td class=\'smalltd\'>'.get_friendly_client_status($cli_id_array['org_client_status']).'</td>';
                $final_html .= '<td class=\'smalltd\'>'.$cli_id_array['org_generated_client_id'].'</td>';
                //$final_html .= '<td class=\'smalltd\'>'.$report_org_name.'</td>';
                //Properly display anonymous SSN
                if ($cli_id_array['ss_number'])
                {
					$final_html .= '<td class=\'smalltd\'>'.stripslashes(get_friendly_text($cli_id_array['ss_number'])).'</td>';
				}
				else
				{
					$final_html .= '<td class=\'smalltd\'>???-??-????</td>';
				}
                
                if ( !$no_links )
				{
					if (strstr( '?', $this_page))
						$page_url_for_extend = $this_page.'&'; 
					else
						$page_url_for_extend = $this_page.'?';
                    $final_html .= "<td class=\"smalltd\"><a class=\"smaller\" href=\"".$system_directory.$page_url_for_extend."add_client_to_household_session=".$cli_id."\">ADD client to View</a></td>";
                }
                $final_html .= '</tr>';
            }
            log_report_activity ( $_SESSION['user_idB'], 'identifier', $cli_id, 'id_lookup_list' );
        }
    }
	$final_html .= '</table>';
    
	return $final_html;
}




?>
Return current item: Homeless Mangement Information System