Allows display of appointments in descending order, take 2.
[openemr.git] / custom / code_types.inc.php
blob11baac2c94ce7ba6223ef4bb1b46ad0f429fd81c
1 <?php
2 /**
3 * Library and data structure to manage Code Types and code type lookups.
5 * The data structure is the $code_types array.
6 * The $code_types array is built from the code_types sql table and provides
7 * abstraction of diagnosis/billing code types. This is desirable
8 * because different countries or fields of practice use different methods for
9 * coding diagnoses, procedures and supplies. Fees will not be relevant where
10 * medical care is socialized.
11 * <pre>Attributes of the $code_types array are:
12 * active - 1 if this code type is activated
13 * id - the numeric identifier of this code type in the codes table
14 * claim - 1 if this code type is used in claims
15 * fee - 1 if fees are used, else 0
16 * mod - the maximum length of a modifier, 0 if modifiers are not used
17 * just - the code type used for justification, empty if none
18 * rel - 1 if other billing codes may be "related" to this code type
19 * nofs - 1 if this code type should NOT appear in the Fee Sheet
20 * diag - 1 if this code type is for diagnosis
21 * proc - 1 if this code type is a procedure/service
22 * label - label used for code type
23 * external - 0 for storing codes in the code table
24 * 1 for storing codes in external ICD10 Diagnosis tables
25 * 2 for storing codes in external SNOMED (RF1) Diagnosis tables
26 * 3 for storing codes in external SNOMED (RF2) Diagnosis tables
27 * 4 for storing codes in external ICD9 Diagnosis tables
28 * 5 for storing codes in external ICD9 Procedure/Service tables
29 * 6 for storing codes in external ICD10 Procedure/Service tables
30 * 7 for storing codes in external SNOMED Clinical Term tables
31 * 8 for storing codes in external SNOMED (RF2) Clinical Term tables (for future)
32 * 9 for storing codes in external SNOMED (RF1) Procedure Term tables
33 * 10 for storing codes in external SNOMED (RF2) Procedure Term tables (for future)
34 * term - 1 if this code type is used as a clinical term
35 * problem - 1 if this code type is used as a medical problem
36 * drug - 1 if this code type is used as a medication
38 * </pre>
40 * Copyright (C) 2006-2010 Rod Roark <rod@sunsetsystems.com>
42 * LICENSE: This program is free software; you can redistribute it and/or
43 * modify it under the terms of the GNU General Public License
44 * as published by the Free Software Foundation; either version 2
45 * of the License, or (at your option) any later version.
46 * This program is distributed in the hope that it will be useful,
47 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
49 * GNU General Public License for more details.
50 * You should have received a copy of the GNU General Public License
51 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
53 * @package OpenEMR
54 * @author Rod Roark <rod@sunsetsystems.com>
55 * @author Brady Miller <brady@sparmy.com>
56 * @author Kevin Yeh <kevin.y@integralemr.com>
57 * @link http://www.open-emr.org
60 require_once(dirname(__FILE__)."/../library/csv_like_join.php");
62 $code_types = array();
63 $default_search_type = '';
64 $ctres = sqlStatement("SELECT * FROM code_types WHERE ct_active=1 ORDER BY ct_seq, ct_key");
65 while ($ctrow = sqlFetchArray($ctres)) {
66 $code_types[$ctrow['ct_key']] = array(
67 'active' => $ctrow['ct_active' ],
68 'id' => $ctrow['ct_id' ],
69 'fee' => $ctrow['ct_fee' ],
70 'mod' => $ctrow['ct_mod' ],
71 'just' => $ctrow['ct_just'],
72 'rel' => $ctrow['ct_rel' ],
73 'nofs' => $ctrow['ct_nofs'],
74 'diag' => $ctrow['ct_diag'],
75 'mask' => $ctrow['ct_mask'],
76 'label'=> ( (empty($ctrow['ct_label'])) ? $ctrow['ct_key'] : $ctrow['ct_label'] ),
77 'external'=> $ctrow['ct_external'],
78 'claim' => $ctrow['ct_claim'],
79 'proc' => $ctrow['ct_proc'],
80 'term' => $ctrow['ct_term'],
81 'problem'=> $ctrow['ct_problem'],
82 'drug'=> $ctrow['ct_drug']
84 if ($default_search_type === '') $default_search_type = $ctrow['ct_key'];
87 /** This array contains metadata describing the arrangement of the external data
88 * tables for storing codes.
90 $code_external_tables=array();
91 define('EXT_COL_CODE','code');
92 define('EXT_COL_DESCRIPTION','description');
93 define('EXT_COL_DESCRIPTION_BRIEF','description_brief');
94 define('EXT_TABLE_NAME','table');
95 define('EXT_FILTER_CLAUSES','filter_clause');
96 define('EXT_VERSION_ORDER','filter_version_order');
97 define('EXT_JOINS','joins');
98 define('JOIN_TABLE','join');
99 define('JOIN_FIELDS','fields');
100 define('DISPLAY_DESCRIPTION',"display_description");
103 * This is a helper function for defining the metadata that describes the tables
105 * @param type $results A reference to the global array which stores all the metadata
106 * @param type $index The external table ID. This corresponds to the value in the code_types table in the ct_external column
107 * @param type $table_name The name of the table which stores the code informattion (e.g. icd9_dx_code
108 * @param type $col_code The name of the column which is the code
109 * @param type $col_description The name of the column which is the description
110 * @param type $col_description_brief The name of the column which is the brief description
111 * @param type $filter_clauses An array of clauses to be included in the search "WHERE" clause that limits results
112 * @param type $version_order How to choose between different revisions of codes
113 * @param type $joins An array which describes additional tables to join as part of a code search.
115 function define_external_table(&$results, $index, $table_name,$col_code, $col_description,$col_description_brief,$filter_clauses=array(),$version_order="",$joins=array(),$display_desc="")
117 $results[$index]=array(EXT_TABLE_NAME=>$table_name,
118 EXT_COL_CODE=>$col_code,
119 EXT_COL_DESCRIPTION=>$col_description,
120 EXT_COL_DESCRIPTION_BRIEF=>$col_description_brief,
121 EXT_FILTER_CLAUSES=>$filter_clauses,
122 EXT_JOINS=>$joins,
123 EXT_VERSION_ORDER=>$version_order,
124 DISPLAY_DESCRIPTION=>$display_desc
127 // In order to treat all the code types the same for lookup_code_descriptions, we include metadata for the original codes table
128 define_external_table($code_external_tables,0,'codes','code','code_text','code_text_short',array(),'id');
130 // ICD9 External Definitions
131 define_external_table($code_external_tables,4,'icd9_dx_code','formatted_dx_code','long_desc','short_desc',array("active='1'"),'revision DESC');
132 define_external_table($code_external_tables,5,'icd9_sg_code','formatted_sg_code','long_desc','short_desc',array("active='1'"),'revision DESC');
133 //**** End ICD9 External Definitions
135 // SNOMED Definitions
136 // For generic SNOMED-CT, there is no need to join with the descriptions table to get a specific description Type
138 // For generic concepts, use the fully specified description (DescriptionType=3) so we can tell the difference between them.
139 define_external_table($code_external_tables,7,'sct_descriptions','ConceptId','Term','Term',array("DescriptionStatus=0","DescriptionType=3"),"");
142 // To determine codes, we need to evaluate data in both the sct_descriptions table, and the sct_concepts table.
143 // the base join with sct_concepts is the same for all types of SNOMED definitions, so we define the common part here
144 $SNOMED_joins=array(JOIN_TABLE=>"sct_concepts",JOIN_FIELDS=>array("sct_descriptions.ConceptId=sct_concepts.ConceptId"));
146 // For disorders, use the preferred term (DescriptionType=1)
147 define_external_table($code_external_tables,2,'sct_descriptions','ConceptId','Term','Term',array("DescriptionStatus=0","DescriptionType=1"),"",array($SNOMED_joins));
148 // Add the filter to choose only disorders. This filter happens as part of the join with the sct_concepts table
149 array_push($code_external_tables[2][EXT_JOINS][0][JOIN_FIELDS],"FullySpecifiedName like '%(disorder)'");
151 // SNOMED-PR definition
152 define_external_table($code_external_tables,9,'sct_descriptions','ConceptId','Term','Term',array("DescriptionStatus=0","DescriptionType=1"),"",array($SNOMED_joins));
153 // Add the filter to choose only procedures. This filter happens as part of the join with the sct_concepts table
154 array_push($code_external_tables[9][EXT_JOINS][0][JOIN_FIELDS],"FullySpecifiedName like '%(procedure)'");
157 //**** End SNOMED Definitions
159 // ICD 10 Definitions
160 define_external_table($code_external_tables,1,'icd10_dx_order_code','formatted_dx_code','long_desc','short_desc',array("active='1'","valid_for_coding = '1'"),'revision DESC');
161 define_external_table($code_external_tables,6,'icd10_pcs_order_code','pcs_code','long_desc','short_desc',array("active='1'","valid_for_coding = '1'"),'revision DESC');
162 //**** End ICD 10 Definitions
165 * This array stores the external table options. See above for $code_types array
166 * 'external' attribute for explanation of the option listings.
167 * @var array
169 $cd_external_options = array(
170 '0' => xl('No'),
171 '4' => xl('ICD9 Diagnosis'),
172 '5' => xl('ICD9 Procedure/Service'),
173 '1' => xl('ICD10 Diagnosis'),
174 '6' => xl('ICD10 Procedure/Service'),
175 '2' => xl('SNOMED (RF1) Diagnosis'),
176 '7' => xl('SNOMED (RF1) Clinical Term'),
177 '9' => xl('SNOMED (RF1) Procedure')
181 * Checks is fee are applicable to any of the code types.
183 * @return boolean
185 function fees_are_used() {
186 global $code_types;
187 foreach ($code_types as $value) { if ($value['fee'] && $value['active']) return true; }
188 return false;
192 * Checks is modifiers are applicable to any of the code types.
193 * (If a code type is not set to show in the fee sheet, then is ignored)
195 * @param boolean $fee_sheet Will ignore code types that are not shown in the fee sheet
196 * @return boolean
198 function modifiers_are_used($fee_sheet=false) {
199 global $code_types;
200 foreach ($code_types as $value) {
201 if ($fee_sheet && !empty($value['nofs'])) continue;
202 if ($value['mod'] && $value['active']) return true;
204 return false;
208 * Checks if justifiers are applicable to any of the code types.
210 * @return boolean
212 function justifiers_are_used() {
213 global $code_types;
214 foreach ($code_types as $value) { if (!empty($value['just']) && $value['active']) return true; }
215 return false;
219 * Checks is related codes are applicable to any of the code types.
221 * @return boolean
223 function related_codes_are_used() {
224 global $code_types;
225 foreach ($code_types as $value) { if ($value['rel'] && $value['active']) return true; }
226 return false;
230 * Convert a code type id (ct_id) to the key string (ct_key)
232 * @param integer $id
233 * @return string
235 function convert_type_id_to_key($id) {
236 global $code_types;
237 foreach ($code_types as $key => $value) {
238 if ($value['id'] == $id) return $key;
243 * Checks if a key string (ct_key) is selected for an element/filter(s)
245 * @param string $key
246 * @param array $filter (array of elements that can include 'active','fee','rel','nofs','diag','claim','proc','term','problem')
247 * @return boolean
249 function check_code_set_filters($key,$filters=array()) {
250 global $code_types;
252 if (empty($filters)) return false;
254 foreach ($filters as $filter) {
255 if ($code_types[$key][$filter] != 1) return false;
258 // Filter was passed
259 return true;
263 * Return listing of pertinent and active code types.
265 * Function will return listing (ct_key) of pertinent
266 * active code types, such as diagnosis codes or procedure
267 * codes in a chosen format. Supported returned formats include
268 * as 1) an array and as 2) a comma-separated lists that has been
269 * process by urlencode() in order to place into URL address safely.
271 * @param string $category category of code types('diagnosis', 'procedure', 'clinical_term', 'active' or 'medical_problem')
272 * @param string $return_format format or returned code types ('array' or 'csv')
273 * @return string/array
275 function collect_codetypes($category,$return_format="array") {
276 global $code_types;
278 $return = array();
280 foreach ($code_types as $ct_key => $ct_arr) {
281 if (!$ct_arr['active']) continue;
283 if ($category == "diagnosis") {
284 if ($ct_arr['diag']) {
285 array_push($return,$ct_key);
288 else if ($category == "procedure") {
289 if ($ct_arr['proc']) {
290 array_push($return,$ct_key);
293 else if ($category == "clinical_term") {
294 if ($ct_arr['term']) {
295 array_push($return,$ct_key);
298 else if ($category == "active") {
299 if ($ct_arr['active']) {
300 array_push($return,$ct_key);
303 else if ($category == "medical_problem") {
304 if ($ct_arr['problem']) {
305 array_push($return,$ct_key);
308 else if ($category == "drug") {
309 if ($ct_arr['drug']) {
310 array_push($return,$ct_key);
313 else {
314 //return nothing since no supported category was chosen
318 if ($return_format == "csv") {
319 //return it as a csv string
320 return csv_like_join($return);
322 else { //$return_format == "array"
323 //return the array
324 return $return;
329 * Return the code information for a specific code.
331 * Function is able to search a variety of code sets. See the code type items in the comments at top
332 * of this page for a listing of the code sets supported.
334 * @param string $form_code_type code set key
335 * @param string $code code
336 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
337 * @return recordset will contain only one item (row).
339 function return_code_information($form_code_type,$code,$active=true) {
340 return code_set_search($form_code_type,$code,false,$active,true);
344 * The main code set searching function.
346 * It will work for searching one or numerous code sets simultaneously.
347 * Note that when searching numerous code sets, you CAN NOT search the PROD
348 * codes; the PROD codes can only be searched by itself.
350 * @param string/array $form_code_type code set key(s) (can either be one key in a string or multiple/one key(s) in an array
351 * @param string $search_term search term
352 * @param integer $limit Number of results to return (NULL means return all)
353 * @param string $category Category of code sets. This WILL OVERRIDE the $form_code_type setting (category options can be found in the collect_codetypes() function above)
354 * @param boolean $active if true, then will only return active entries
355 * @param array $modes Holds the search modes to process along with the order of processing (if NULL, then default behavior is sequential code then description search)
356 * @param boolean $count if true, then will only return the number of entries
357 * @param integer $start Query start limit (for pagination) (Note this setting will override the above $limit parameter)
358 * @param integer $number Query number returned (for pagination) (Note this setting will override the above $limit parameter)
359 * @param array $filter_elements Array that contains elements to filter
360 * @return recordset/integer Will contain either a integer(if counting) or the results (recordset)
362 function main_code_set_search($form_code_type,$search_term,$limit=NULL,$category=NULL,$active=true,$modes=NULL,$count=false,$start=NULL,$number=NULL,$filter_elements=array()) {
364 // check for a category
365 if (!empty($category)) {
366 $form_code_type = collect_codetypes($category,"array");
369 // do the search
370 if (!empty($form_code_type)) {
371 if ( is_array($form_code_type) && (count($form_code_type) > 1) ) {
372 // run the multiple code set search
373 return multiple_code_set_search($form_code_type,$search_term,$limit,$modes,$count,$active,$start,$number,$filter_elements);
375 if ( is_array($form_code_type) && (count($form_code_type) == 1) ) {
376 // prepare the variable (ie. convert the one array item to a string) for the non-multiple code set search
377 $form_code_type = $form_code_type[0];
379 // run the non-multiple code set search
380 return sequential_code_set_search($form_code_type,$search_term,$limit,$modes,$count,$active,$start,$number,$filter_elements);
385 * Main "internal" code set searching function.
387 * Function is able to search a variety of code sets. See the 'external' items in the comments at top
388 * of this page for a listing of the code sets supported. Also note that Products (using PROD as code type)
389 * is also supported. (This function is not meant to be called directly)
391 * @param string $form_code_type code set key (special keywords are PROD) (Note --ALL-- has been deprecated and should be run through the multiple_code_set_search() function instead)
392 * @param string $search_term search term
393 * @param boolean $count if true, then will only return the number of entries
394 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
395 * @param boolean $return_only_one if true, then will only return one perfect matching item
396 * @param integer $start Query start limit
397 * @param integer $number Query number returned
398 * @param array $filter_elements Array that contains elements to filter
399 * @param integer $limit Number of results to return (NULL means return all); note this is ignored if set $start/number
400 * @param array $mode 'default' mode searches code and description, 'code' mode only searches code, 'description' mode searches description (and separates words); note this is ignored if set $return_only_one to TRUE
401 * @param array $return_query This is a mode that will only return the query (everything except for the LIMIT is included) (returned as an array to include the query string and binding array)
402 * @return recordset/integer/array
404 function code_set_search($form_code_type,$search_term="",$count=false,$active=true,$return_only_one=false,$start=NULL,$number=NULL,$filter_elements=array(),$limit=NULL,$mode='default',$return_query=false) {
405 global $code_types,$code_external_tables;
407 // Figure out the appropriate limit clause
408 $limit_query = limit_query_string($limit,$start,$number,$return_only_one);
410 // build the filter_elements sql code
411 $query_filter_elements="";
412 if (!empty($filter_elements)) {
413 foreach ($filter_elements as $key => $element) {
414 $query_filter_elements .= " AND codes." . add_escape_custom($key) . "=" . "'" . add_escape_custom($element) . "' ";
418 if ($form_code_type == 'PROD') { // Search for products/drugs
419 if ($count) {
420 $query = "SELECT count(dt.drug_id) as count ";
422 else {
423 $query = "SELECT dt.drug_id, dt.selector, d.name ";
425 $query .= "FROM drug_templates AS dt, drugs AS d WHERE " .
426 "( d.name LIKE ? OR " .
427 "dt.selector LIKE ? ) " .
428 "AND d.drug_id = dt.drug_id " .
429 "ORDER BY d.name, dt.selector, dt.drug_id $limit_query";
430 $res = sqlStatement($query, array("%".$search_term."%", "%".$search_term."%") );
432 else { // Start a codes search
433 // We are looking up the external table id here. An "unset" value gets treated as 0(zero) without this test. This way we can differentiate between "unset" and explicitly zero.
434 $table_id=isset($code_types[$form_code_type]['external']) ? intval(($code_types[$form_code_type]['external'])) : -9999 ;
435 if($table_id>=0) // We found a definition for the given code search, so start building the query
437 // Place the common columns variable here since all check codes table
438 $common_columns=" codes.id, codes.code_type, codes.modifier, codes.units, codes.fee, " .
439 "codes.superbill, codes.related_code, codes.taxrates, codes.cyp_factor, " .
440 "codes.active, codes.reportable, codes.financial_reporting, ";
441 $columns = $common_columns . "'" . add_escape_custom($form_code_type) . "' as code_type_name ";
443 $active_query = '';
444 if ($active) {
445 // Only filter for active codes. Only the active column in the joined table
446 // is affected by this parameter. Any filtering as a result of "active" status
447 // in the external table itself is always applied. I am implementing the behavior
448 // just as was done prior to the refactor
449 // - Kevin Yeh
450 // If there is no entry in codes sql table, then default to active
451 // (this is reason for including NULL below)
452 if ($table_id==0) {
453 // Search from default codes table
454 $active_query=" AND codes.active = 1 ";
456 else {
457 // Search from external tables
458 $active_query=" AND (codes.active = 1 || codes.active IS NULL) ";
462 // Get/set the basic metadata information
463 $table_info=$code_external_tables[$table_id];
464 $table=$table_info[EXT_TABLE_NAME];
465 $table_dot=$table.".";
466 $code_col=$table_info[EXT_COL_CODE];
467 $code_text_col=$table_info[EXT_COL_DESCRIPTION];
468 $code_text_short_col=$table_info[EXT_COL_DESCRIPTION_BRIEF];
469 if ($table_id==0) {
470 $table_info[EXT_FILTER_CLAUSES]=array("code_type=".$code_types[$form_code_type]['id']); // Add a filter for the code type
472 $code_external = $code_types[$form_code_type]['external'];
474 // If the description is supposed to come from "joined" table instead of the "main",
475 // the metadata defines a DISPLAY_DESCRIPTION element, and we use that to build up the query
476 if($table_info[DISPLAY_DESCRIPTION]!="")
478 $display_description=$table_info[DISPLAY_DESCRIPTION];
479 $display_description_brief=$table_info[DISPLAY_DESCRIPTION];
481 else
483 $display_description=$table_dot.$code_text_col;
484 $display_description_brief=$table_dot.$code_text_short_col;
486 // Ensure the external table exists
487 $check_table = sqlQuery("SHOW TABLES LIKE '".$table."'");
488 if ( (empty($check_table)) ) {HelpfulDie("Missing table in code set search:".$table);}
490 $sql_bind_array = array();
491 if ($count) {
492 // only collecting a count
493 $query = "SELECT count(".$table_dot.$code_col . ") as count ";
495 else {
496 $query = "SELECT '" . $code_external ."' as code_external, " .
497 $table_dot.$code_col . " as code, " .
498 $display_description . " as code_text, " .
499 $display_description_brief . " as code_text_short, " .
500 $columns . " ";
502 if ($table_id==0) {
503 // Search from default codes table
504 $query .= " FROM ".$table." ";
506 else {
507 // Search from external tables
508 $query .= " FROM ".$table.
509 " LEFT OUTER JOIN `codes` " .
510 " ON ".$table_dot.$code_col." = codes.code AND codes.code_type = ? ";
511 array_push($sql_bind_array,$code_types[$form_code_type]['id']);
514 foreach($table_info[EXT_JOINS] as $join_info)
516 $join_table=$join_info[JOIN_TABLE];
517 $check_table = sqlQuery("SHOW TABLES LIKE '".$join_table."'");
518 if ( (empty($check_table)) ) {HelpfulDie("Missing join table in code set search:".$join_table);}
519 $query.=" INNER JOIN ". $join_table;
520 $query.=" ON ";
521 $not_first=false;
522 foreach($join_info[JOIN_FIELDS] as $field)
524 if($not_first)
526 $query.=" AND ";
528 $query.=$field;
529 $not_first=true;
533 // Setup the where clause based on MODE
534 $query.= " WHERE ";
535 if ($return_only_one) {
536 $query .= $table_dot.$code_col." = ? ";
537 array_push($sql_bind_array,$search_term);
539 else if($mode=="code") {
540 $query.= $table_dot.$code_col." like ? ";
541 array_push($sql_bind_array,$search_term."%");
543 else if($mode=="description"){
544 $description_keywords=preg_split("/ /",$search_term,-1,PREG_SPLIT_NO_EMPTY);
545 $query.="(1=1 ";
546 foreach($description_keywords as $keyword)
548 $query.= " AND ".$table_dot.$code_text_col." LIKE ? ";
549 array_push($sql_bind_array,"%".$keyword."%");
551 $query.=")";
553 else { // $mode == "default"
554 $query .= "(".$table_dot.$code_text_col. " LIKE ? OR ".$table_dot.$code_col. " LIKE ?) ";
555 array_push($sql_bind_array,"%".$search_term."%","%".$search_term."%");
557 // Done setting up the where clause by mode
559 // Add the metadata related filter clauses
560 foreach($table_info[EXT_FILTER_CLAUSES] as $filter_clause)
562 $query.=" AND ";
563 $dot_location=strpos($filter_clause,".");
564 if($dot_location!==false) {
565 // The filter clause already includes a table specifier, so don't add one
566 $query .=$filter_clause;
568 else {
569 $query .=$table_dot.$filter_clause;
573 $query .=$active_query . $query_filter_elements;
575 $query .= " ORDER BY ".$table_dot.$code_col."+0,".$table_dot.$code_col;
577 if ($return_query) {
578 // Just returning the actual query without the LIMIT information in it. This
579 // information can then be used to combine queries of different code types
580 // via the mysql UNION command. Returning an array to contain the query string
581 // and the binding parameters.
582 return array('query'=>$query,'binds'=>$sql_bind_array);
585 $query .= $limit_query;
587 $res = sqlStatement($query,$sql_bind_array);
589 else
591 HelpfulDie("Code type not active or not defined:".$join_info[JOIN_TABLE]);
593 } // End specific code type search
595 if (isset($res)) {
596 if ($count) {
597 // just return the count
598 $ret = sqlFetchArray($res);
599 return $ret['count'];
601 else {
602 // return the data
603 return $res;
609 * Lookup Code Descriptions for one or more billing codes.
611 * Function is able to lookup code descriptions from a variety of code sets. See the 'external'
612 * items in the comments at top of this page for a listing of the code sets supported.
614 * @param string $codes Is of the form "type:code;type:code; etc.".
615 * @param string $desc_detail Can choose either the normal description('code_text') or the brief description('code_text_short').
616 * @return string Is of the form "description;description; etc.".
618 function lookup_code_descriptions($codes,$desc_detail="code_text") {
619 global $code_types, $code_external_tables;
621 // ensure $desc_detail is set properly
622 if ( ($desc_detail != "code_text") && ($desc_detail != "code_text_short") ) {
623 $desc_detail="code_text";
626 $code_text = '';
627 if (!empty($codes)) {
628 $relcodes = explode(';', $codes);
629 foreach ($relcodes as $codestring) {
630 if ($codestring === '') continue;
631 list($codetype, $code) = explode(':', $codestring);
632 $table_id=$code_types[$codetype]['external'];
633 if(isset($code_external_tables[$table_id]))
635 $table_info=$code_external_tables[$table_id];
636 $table_name=$table_info[EXT_TABLE_NAME];
637 $code_col=$table_info[EXT_COL_CODE];
638 $desc_col= $table_info[DISPLAY_DESCRIPTION]=="" ? $table_info[EXT_COL_DESCRIPTION] : $table_info[DISPLAY_DESCRIPTION];
639 $desc_col_short= $table_info[DISPLAY_DESCRIPTION]=="" ? $table_info[EXT_COL_DESCRIPTION_BRIEF] : $table_info[DISPLAY_DESCRIPTION];
640 $sqlArray = array();
641 $sql = "SELECT ".$desc_col." as code_text,".$desc_col_short." as code_text_short FROM ".$table_name;
643 // include the "JOINS" so that we get the preferred term instead of the FullySpecifiedName when appropriate.
644 foreach($table_info[EXT_JOINS] as $join_info)
646 $join_table=$join_info[JOIN_TABLE];
647 $check_table = sqlQuery("SHOW TABLES LIKE '".$join_table."'");
648 if ( (empty($check_table)) ) {HelpfulDie("Missing join table in code set search:".$join_table);}
649 $sql.=" INNER JOIN ". $join_table;
650 $sql.=" ON ";
651 $not_first=false;
652 foreach($join_info[JOIN_FIELDS] as $field)
654 if($not_first)
656 $sql.=" AND ";
658 $sql.=$field;
659 $not_first=true;
663 $sql.=" WHERE ";
666 // Start building up the WHERE clause
668 // When using the external codes table, we have to filter by the code_type. (All the other tables only contain one type)
669 if ($table_id==0) { $sql .= " code_type = '".add_escape_custom($code_types[$codetype]['id'])."' AND "; }
671 // Specify the code in the query.
672 $sql .= $table_name.".".$code_col."=? ";
673 array_push($sqlArray,$code);
675 // We need to include the filter clauses
676 // For SNOMED and SNOMED-CT this ensures that we get the Preferred Term or the Fully Specified Term as appropriate
677 // It also prevents returning "inactive" results
678 foreach($table_info[EXT_FILTER_CLAUSES] as $filter_clause)
680 $sql.= " AND ".$filter_clause;
682 // END building the WHERE CLAUSE
685 if($table_info[EXT_VERSION_ORDER]){$sql .= " ORDER BY ".$table_info[EXT_VERSION_ORDER];}
687 $sql .= " LIMIT 1";
688 $crow = sqlQuery($sql,$sqlArray);
689 if (!empty($crow[$desc_detail])) {
690 if ($code_text) $code_text .= '; ';
691 $code_text .= $crow[$desc_detail];
695 else {
696 //using an external code that is not yet supported, so skip.
700 return $code_text;
704 * Sequential code set "internal" searching function
706 * Function is basically a wrapper of the code_set_search() function to support
707 * a optimized searching models. The default mode will:
708 * Searches codes first; then if no hits, it will then search the descriptions
709 * (which are separated by each word in the code_set_search() function).
710 * (This function is not meant to be called directly)
712 * @param string $form_code_type code set key (special keyword is PROD) (Note --ALL-- has been deprecated and should be run through the multiple_code_set_search() function instead)
713 * @param string $search_term search term
714 * @param integer $limit Number of results to return (NULL means return all)
715 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
716 * @param boolean $count if true, then will only return the number of entries
717 * @param boolean $active if true, then will only return active entries
718 * @param integer $start Query start limit (for pagination)
719 * @param integer $number Query number returned (for pagination)
720 * @param array $filter_elements Array that contains elements to filter
721 * @param string $is_hit_mode This is a mode that simply returns the name of the mode if results were found
722 * @return recordset/integer/string
724 function sequential_code_set_search($form_code_type,$search_term,$limit=NULL,$modes=NULL,$count=false,$active=true,$start=NULL,$number=NULL,$filter_elements=array(),$is_hit_mode=false) {
725 // Set the default behavior that is described in above function comments
726 if (empty($modes)) {
727 $modes=array('code','description');
730 // Return the Search Results (loop through each mode in order)
731 foreach ($modes as $mode) {
732 $res = code_set_search($form_code_type,$search_term,$count,$active,false,$start,$number,$filter_elements,$limit,$mode);
733 if ( ($count && $res>0) || (!$count && sqlNumRows($res)>0) ) {
734 if ($is_hit_mode) {
735 // just return the mode
736 return $mode;
738 else {
739 // returns the count number if count is true or returns the data if count is false
740 return $res;
747 * Code set searching "internal" function for when searching multiple code sets.
749 * It will also work for one code set search, although not meant for this.
750 * (This function is not meant to be called directly)
752 * @param array $form_code_types code set keys (will default to checking all active code types if blank)
753 * @param string $search_term search term
754 * @param integer $limit Number of results to return (NULL means return all)
755 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
756 * @param boolean $count if true, then will only return the number of entries
757 * @param boolean $active if true, then will only return active entries
758 * @param integer $start Query start limit (for pagination)
759 * @param integer $number Query number returned (for pagination)
760 * @param array $filter_elements Array that contains elements to filter
761 * @return recordset/integer
763 function multiple_code_set_search($form_code_types=array(),$search_term,$limit=NULL,$modes=NULL,$count=false,$active=true,$start=NULL,$number=NULL,$filter_elements=array()) {
765 if (empty($form_code_types)) {
766 // Collect the active code types
767 $form_code_types = collect_codetypes("active","array");
770 if ($count) {
771 //start the counter
772 $counter = 0;
774 else {
775 // Figure out the appropriate limit clause
776 $limit_query = limit_query_string($limit,$start,$number);
778 // Prepare the sql bind array
779 $sql_bind_array = array();
781 // Start the query string
782 $query = "SELECT * FROM ((";
785 // Loop through each code type
786 $flag_first = true;
787 $flag_hit = false; //ensure there is a hit to avoid trying an empty query
788 foreach ($form_code_types as $form_code_type) {
789 // see if there is a hit
790 $mode_hit = NULL;
791 // only use the count method here, since it's much more efficient than doing the actual query
792 $mode_hit = sequential_code_set_search($form_code_type,$search_term,NULL,$modes,true,$active,NULL,NULL,$filter_elements,true);
793 if ($mode_hit) {
794 if ($count) {
795 // count the hits
796 $count_hits = code_set_search($form_code_type,$search_term,$count,$active,false,NULL,NULL,$filter_elements,NULL,$mode_hit);
797 // increment the counter
798 $counter += $count_hits;
800 else {
801 $flag_hit = true;
802 // build the query
803 $return_query = code_set_search($form_code_type,$search_term,$count,$active,false,NULL,NULL,$filter_elements,NULL,$mode_hit,true);
804 if (!empty($sql_bind_array)) {
805 $sql_bind_array = array_merge($sql_bind_array,$return_query['binds']);
807 else {
808 $sql_bind_array = $return_query['binds'];
810 if (!$flag_first) {
811 $query .= ") UNION ALL (";
813 $query .= $return_query['query'];
815 $flag_first = false;
819 if ($count) {
820 //return the count
821 return $counter;
823 else {
824 // Finish the query string
825 $query .= ")) as atari $limit_query";
827 // Process and return the query (if there was a hit)
828 if ($flag_hit) {
829 return sqlStatement($query,$sql_bind_array);
835 * Returns the limit to be used in the sql query for code set searches.
837 * @param integer $limit Number of results to return (NULL means return all)
838 * @param integer $start Query start limit (for pagination)
839 * @param integer $number Query number returned (for pagination)
840 * @param boolean $return_only_one if true, then will only return one perfect matching item
841 * @return recordset/integer
843 function limit_query_string($limit=NULL,$start=NULL,$number=NULL,$return_only_one=false) {
844 if ( !is_null($start) && !is_null($number) ) {
845 // For pagination of results
846 $limit_query = " LIMIT $start, $number ";
848 else if (!is_null($limit)) {
849 $limit_query = " LIMIT $limit ";
851 else {
852 // No pagination and no limit
853 $limit_query = '';
855 if ($return_only_one) {
856 // Only return one result (this is where only matching for exact code match)
857 // Note this overrides the above limit settings
858 $limit_query = " LIMIT 1 ";
860 return $limit_query;