add default search type to session for fee sheet search for add'l codes (#4421)
[openemr.git] / custom / code_types.inc.php
blob36551ecba6b4c028675e0cce057a1bdeeb3d84b6
1 <?php
3 /**
4 * Library and data structure to manage Code Types and code type lookups.
6 * The data structure is the $code_types array.
7 * The $code_types array is built from the code_types sql table and provides
8 * abstraction of diagnosis/billing code types. This is desirable
9 * because different countries or fields of practice use different methods for
10 * coding diagnoses, procedures and supplies. Fees will not be relevant where
11 * medical care is socialized.
12 * <pre>Attributes of the $code_types array are:
13 * active - 1 if this code type is activated
14 * id - the numeric identifier of this code type in the codes table
15 * claim - 1 if this code type is used in claims
16 * fee - 1 if fees are used, else 0
17 * mod - the maximum length of a modifier, 0 if modifiers are not used
18 * just - the code type used for justification, empty if none
19 * rel - 1 if other billing codes may be "related" to this code type
20 * nofs - 1 if this code type should NOT appear in the Fee Sheet
21 * diag - 1 if this code type is for diagnosis
22 * proc - 1 if this code type is a procedure/service
23 * label - label used for code type
24 * external - 0 for storing codes in the code table
25 * 1 for storing codes in external ICD10 Diagnosis tables
26 * 2 for storing codes in external SNOMED (RF1) Diagnosis tables
27 * 3 for storing codes in external SNOMED (RF2) Diagnosis tables
28 * 4 for storing codes in external ICD9 Diagnosis tables
29 * 5 for storing codes in external ICD9 Procedure/Service tables
30 * 6 for storing codes in external ICD10 Procedure/Service tables
31 * 7 for storing codes in external SNOMED Clinical Term tables
32 * 8 for storing codes in external SNOMED (RF2) Clinical Term tables (for future)
33 * 9 for storing codes in external SNOMED (RF1) Procedure Term tables
34 * 10 for storing codes in external SNOMED (RF2) Procedure Term tables (for future)
35 * term - 1 if this code type is used as a clinical term
36 * problem - 1 if this code type is used as a medical problem
37 * drug - 1 if this code type is used as a medication
39 * </pre>
42 * @package OpenEMR
43 * @link https://www.open-emr.org
44 * @author Rod Roark <rod@sunsetsystems.com>
45 * @author Brady Miller <brady.g.miller@gmail.com>
46 * @author Kevin Yeh <kevin.y@integralemr.com>
47 * @copyright Copyright (c) 2006-2010 Rod Roark <rod@sunsetsystems.com>
48 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
49 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
52 require_once(dirname(__FILE__) . "/../library/csv_like_join.php");
54 $code_types = array();
55 global $code_types;
56 $ctres = sqlStatement("SELECT * FROM code_types WHERE ct_active=1 ORDER BY ct_seq, ct_key");
57 while ($ctrow = sqlFetchArray($ctres)) {
58 $code_types[$ctrow['ct_key']] = array(
59 'active' => $ctrow['ct_active' ],
60 'id' => $ctrow['ct_id' ],
61 'fee' => $ctrow['ct_fee' ],
62 'mod' => $ctrow['ct_mod' ],
63 'just' => $ctrow['ct_just'],
64 'rel' => $ctrow['ct_rel' ],
65 'nofs' => $ctrow['ct_nofs'],
66 'diag' => $ctrow['ct_diag'],
67 'mask' => $ctrow['ct_mask'],
68 'label' => ( (empty($ctrow['ct_label'])) ? $ctrow['ct_key'] : $ctrow['ct_label'] ),
69 'external' => $ctrow['ct_external'],
70 'claim' => $ctrow['ct_claim'],
71 'proc' => $ctrow['ct_proc'],
72 'term' => $ctrow['ct_term'],
73 'problem' => $ctrow['ct_problem'],
74 'drug' => $ctrow['ct_drug']
76 if (!array_key_exists($GLOBALS['default_search_code_type'], $code_types)) {
77 reset($code_types);
78 $$GLOBALS['default_search_code_type'] = key($code_types);
82 /** This array contains metadata describing the arrangement of the external data
83 * tables for storing codes.
85 $code_external_tables = array();
86 global $code_external_tables;
87 define('EXT_COL_CODE', 'code');
88 define('EXT_COL_DESCRIPTION', 'description');
89 define('EXT_COL_DESCRIPTION_BRIEF', 'description_brief');
90 define('EXT_TABLE_NAME', 'table');
91 define('EXT_FILTER_CLAUSES', 'filter_clause');
92 define('EXT_VERSION_ORDER', 'filter_version_order');
93 define('EXT_JOINS', 'joins');
94 define('JOIN_TABLE', 'join');
95 define('JOIN_FIELDS', 'fields');
96 define('DISPLAY_DESCRIPTION', "display_description");
98 /**
99 * This is a helper function for defining the metadata that describes the tables
101 * @param type $results A reference to the global array which stores all the metadata
102 * @param type $index The external table ID. This corresponds to the value in the code_types table in the ct_external column
103 * @param type $table_name The name of the table which stores the code informattion (e.g. icd9_dx_code
104 * @param type $col_code The name of the column which is the code
105 * @param type $col_description The name of the column which is the description
106 * @param type $col_description_brief The name of the column which is the brief description
107 * @param type $filter_clauses An array of clauses to be included in the search "WHERE" clause that limits results
108 * @param type $version_order How to choose between different revisions of codes
109 * @param type $joins An array which describes additional tables to join as part of a code search.
111 function define_external_table(&$results, $index, $table_name, $col_code, $col_description, $col_description_brief, $filter_clauses = array(), $version_order = "", $joins = array(), $display_desc = "")
113 $results[$index] = array(EXT_TABLE_NAME => $table_name,
114 EXT_COL_CODE => $col_code,
115 EXT_COL_DESCRIPTION => $col_description,
116 EXT_COL_DESCRIPTION_BRIEF => $col_description_brief,
117 EXT_FILTER_CLAUSES => $filter_clauses,
118 EXT_JOINS => $joins,
119 EXT_VERSION_ORDER => $version_order,
120 DISPLAY_DESCRIPTION => $display_desc
123 // In order to treat all the code types the same for lookup_code_descriptions, we include metadata for the original codes table
124 define_external_table($code_external_tables, 0, 'codes', 'code', 'code_text', 'code_text_short', array(), 'id');
126 // ICD9 External Definitions
127 define_external_table($code_external_tables, 4, 'icd9_dx_code', 'formatted_dx_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
128 define_external_table($code_external_tables, 5, 'icd9_sg_code', 'formatted_sg_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
129 //**** End ICD9 External Definitions
131 // SNOMED Definitions
132 // For generic SNOMED-CT, there is no need to join with the descriptions table to get a specific description Type
134 // For generic concepts, use the fully specified description (DescriptionType=3) so we can tell the difference between them.
135 define_external_table($code_external_tables, 7, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=3"), "");
137 // To determine codes, we need to evaluate data in both the sct_descriptions table, and the sct_concepts table.
138 // the base join with sct_concepts is the same for all types of SNOMED definitions, so we define the common part here
139 $SNOMED_joins = array(JOIN_TABLE => "sct_concepts",JOIN_FIELDS => array("sct_descriptions.ConceptId=sct_concepts.ConceptId"));
141 // For disorders, use the preferred term (DescriptionType=1)
142 define_external_table($code_external_tables, 2, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=1"), "", array($SNOMED_joins));
143 // Add the filter to choose only disorders. This filter happens as part of the join with the sct_concepts table
144 array_push($code_external_tables[2][EXT_JOINS][0][JOIN_FIELDS], "FullySpecifiedName like '%(disorder)'");
146 // SNOMED-PR definition
147 define_external_table($code_external_tables, 9, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=1"), "", array($SNOMED_joins));
148 // Add the filter to choose only procedures. This filter happens as part of the join with the sct_concepts table
149 array_push($code_external_tables[9][EXT_JOINS][0][JOIN_FIELDS], "FullySpecifiedName like '%(procedure)'");
151 // SNOMED RF2 definitions
152 define_external_table($code_external_tables, 11, 'sct2_description', 'conceptId', 'term', 'term', array("active=1"), "");
153 if (isSnomedSpanish()) {
154 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(trastorno)'"), "");
155 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedimiento)'"), "");
156 } else {
157 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(disorder)'"), "");
158 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedure)'"), "");
161 //**** End SNOMED Definitions
163 // ICD 10 Definitions
164 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');
165 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');
166 //**** End ICD 10 Definitions
169 * This array stores the external table options. See above for $code_types array
170 * 'external' attribute for explanation of the option listings.
171 * @var array
173 global $ct_external_options;
174 $ct_external_options = array(
175 '0' => xl('No'),
176 '4' => xl('ICD9 Diagnosis'),
177 '5' => xl('ICD9 Procedure/Service'),
178 '1' => xl('ICD10 Diagnosis'),
179 '6' => xl('ICD10 Procedure/Service'),
180 '2' => xl('SNOMED (RF1) Diagnosis'),
181 '7' => xl('SNOMED (RF1) Clinical Term'),
182 '9' => xl('SNOMED (RF1) Procedure'),
183 '10' => xl('SNOMED (RF2) Diagnosis'),
184 '11' => xl('SNOMED (RF2) Clinical Term'),
185 '12' => xl('SNOMED (RF2) Procedure')
189 * Checks to see if using spanish snomed
191 function isSnomedSpanish()
193 // See if most recent SNOMED entry is International:Spanish
194 $sql = sqlQuery("SELECT `revision_version` FROM `standardized_tables_track` WHERE `name` = 'SNOMED' ORDER BY `id` DESC");
195 if ((!empty($sql)) && ($sql['revision_version'] == "International:Spanish")) {
196 return true;
198 return false;
202 * Checks is fee are applicable to any of the code types.
204 * @return boolean
206 function fees_are_used()
208 global $code_types;
209 foreach ($code_types as $value) {
210 if ($value['fee'] && $value['active']) {
211 return true;
215 return false;
219 * Checks if modifiers are applicable to any of the code types.
220 * (If a code type is not set to show in the fee sheet, then is ignored)
222 * @param boolean $fee_sheet Will ignore code types that are not shown in the fee sheet
223 * @return boolean
225 function modifiers_are_used($fee_sheet = false)
227 global $code_types;
228 foreach ($code_types as $value) {
229 if ($fee_sheet && !empty($value['nofs'])) {
230 continue;
233 if ($value['mod'] && $value['active']) {
234 return true;
238 return false;
242 * Checks if justifiers are applicable to any of the code types.
244 * @return boolean
246 function justifiers_are_used()
248 global $code_types;
249 foreach ($code_types as $value) {
250 if (!empty($value['just']) && $value['active']) {
251 return true;
255 return false;
259 * Checks is related codes are applicable to any of the code types.
261 * @return boolean
263 function related_codes_are_used()
265 global $code_types;
266 foreach ($code_types as $value) {
267 if ($value['rel'] && $value['active']) {
268 return true;
272 return false;
276 * Convert a code type id (ct_id) to the key string (ct_key)
278 * @param integer $id
279 * @return string
281 function convert_type_id_to_key($id)
283 global $code_types;
284 foreach ($code_types as $key => $value) {
285 if ($value['id'] == $id) {
286 return $key;
292 * Checks to see if code allows justification (ct_just)
294 * @param string $key
295 * @return boolean
297 function check_is_code_type_justify($key)
299 global $code_types;
301 if (!empty($code_types[$key]['just'])) {
302 return true;
303 } else {
304 return false;
309 * Checks if a key string (ct_key) is selected for an element/filter(s)
311 * @param string $key
312 * @param array $filter (array of elements that can include 'active','fee','rel','nofs','diag','claim','proc','term','problem')
313 * @return boolean
315 function check_code_set_filters($key, $filters = array())
317 global $code_types;
319 if (empty($filters)) {
320 return false;
323 foreach ($filters as $filter) {
324 if ($code_types[$key][$filter] != 1) {
325 return false;
329 // Filter was passed
330 return true;
334 * Return listing of pertinent and active code types.
336 * Function will return listing (ct_key) of pertinent
337 * active code types, such as diagnosis codes or procedure
338 * codes in a chosen format. Supported returned formats include
339 * as 1) an array and as 2) a comma-separated lists that has been
340 * process by urlencode() in order to place into URL address safely.
342 * @param string $category category of code types('diagnosis', 'procedure', 'clinical_term', 'active' or 'medical_problem')
343 * @param string $return_format format or returned code types ('array' or 'csv')
344 * @return string/array
346 function collect_codetypes($category, $return_format = "array")
348 global $code_types;
350 $return = array();
352 foreach ($code_types as $ct_key => $ct_arr) {
353 if (!$ct_arr['active']) {
354 continue;
357 if ($category == "diagnosis") {
358 if ($ct_arr['diag']) {
359 array_push($return, $ct_key);
361 } elseif ($category == "procedure") {
362 if ($ct_arr['proc']) {
363 array_push($return, $ct_key);
365 } elseif ($category == "clinical_term") {
366 if ($ct_arr['term']) {
367 array_push($return, $ct_key);
369 } elseif ($category == "active") {
370 if ($ct_arr['active']) {
371 array_push($return, $ct_key);
373 } elseif ($category == "medical_problem") {
374 if ($ct_arr['problem']) {
375 array_push($return, $ct_key);
377 } elseif ($category == "drug") {
378 if ($ct_arr['drug']) {
379 array_push($return, $ct_key);
381 } else {
382 //return nothing since no supported category was chosen
386 if ($return_format == "csv") {
387 //return it as a csv string
388 return csv_like_join($return);
389 } else { //$return_format == "array"
390 //return the array
391 return $return;
396 * Return the code information for a specific code.
398 * Function is able to search a variety of code sets. See the code type items in the comments at top
399 * of this page for a listing of the code sets supported.
401 * @param string $form_code_type code set key
402 * @param string $code code
403 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
404 * @return recordset will contain only one item (row).
406 function return_code_information($form_code_type, $code, $active = true)
408 return code_set_search($form_code_type, $code, false, $active, true);
412 * The main code set searching function.
414 * It will work for searching one or numerous code sets simultaneously.
415 * Note that when searching numerous code sets, you CAN NOT search the PROD
416 * codes; the PROD codes can only be searched by itself.
418 * @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
419 * @param string $search_term search term
420 * @param integer $limit Number of results to return (NULL means return all)
421 * @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)
422 * @param boolean $active if true, then will only return active entries
423 * @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)
424 * @param boolean $count if true, then will only return the number of entries
425 * @param integer $start Query start limit (for pagination) (Note this setting will override the above $limit parameter)
426 * @param integer $number Query number returned (for pagination) (Note this setting will override the above $limit parameter)
427 * @param array $filter_elements Array that contains elements to filter
428 * @return recordset/integer Will contain either a integer(if counting) or the results (recordset)
430 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())
433 // check for a category
434 if (!empty($category)) {
435 $form_code_type = collect_codetypes($category, "array");
438 // do the search
439 if (!empty($form_code_type)) {
440 if (is_array($form_code_type) && (count($form_code_type) > 1)) {
441 // run the multiple code set search
442 return multiple_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
445 if (is_array($form_code_type) && (count($form_code_type) == 1)) {
446 // prepare the variable (ie. convert the one array item to a string) for the non-multiple code set search
447 $form_code_type = $form_code_type[0];
450 // run the non-multiple code set search
451 return sequential_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
456 * Main "internal" code set searching function.
458 * Function is able to search a variety of code sets. See the 'external' items in the comments at top
459 * of this page for a listing of the code sets supported. Also note that Products (using PROD as code type)
460 * is also supported. (This function is not meant to be called directly)
462 * @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)
463 * @param string $search_term search term
464 * @param boolean $count if true, then will only return the number of entries
465 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
466 * @param boolean $return_only_one if true, then will only return one perfect matching item
467 * @param integer $start Query start limit
468 * @param integer $number Query number returned
469 * @param array $filter_elements Array that contains elements to filter
470 * @param integer $limit Number of results to return (NULL means return all); note this is ignored if set $start/number
471 * @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
472 * @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)
473 * @return recordset/integer/array
475 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)
477 global $code_types, $code_external_tables;
479 // Figure out the appropriate limit clause
480 $limit_query = limit_query_string($limit, $start, $number, $return_only_one);
482 // build the filter_elements sql code
483 $query_filter_elements = "";
484 if (!empty($filter_elements)) {
485 foreach ($filter_elements as $key => $element) {
486 $query_filter_elements .= " AND codes." . add_escape_custom($key) . "=" . "'" . add_escape_custom($element) . "' ";
490 if ($form_code_type == 'PROD') { // Search for products/drugs
491 if ($count) {
492 $query = "SELECT count(dt.drug_id) as count ";
493 } else {
494 $query = "SELECT dt.drug_id, dt.selector, d.name ";
497 $query .= "FROM drug_templates AS dt, drugs AS d WHERE " .
498 "( d.name LIKE ? OR " .
499 "dt.selector LIKE ? ) " .
500 "AND d.drug_id = dt.drug_id " .
501 "ORDER BY d.name, dt.selector, dt.drug_id $limit_query";
502 $res = sqlStatement($query, array("%" . $search_term . "%", "%" . $search_term . "%"));
503 } else { // Start a codes search
504 // 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.
505 $table_id = isset($code_types[$form_code_type]['external']) ? intval(($code_types[$form_code_type]['external'])) : -9999 ;
506 if ($table_id >= 0) { // We found a definition for the given code search, so start building the query
507 // Place the common columns variable here since all check codes table
508 $common_columns = " codes.id, codes.code_type, codes.modifier, codes.units, codes.fee, " .
509 "codes.superbill, codes.related_code, codes.taxrates, codes.cyp_factor, " .
510 "codes.active, codes.reportable, codes.financial_reporting, codes.revenue_code, ";
511 $columns = $common_columns . "'" . add_escape_custom($form_code_type) . "' as code_type_name ";
513 $active_query = '';
514 if ($active) {
515 // Only filter for active codes. Only the active column in the joined table
516 // is affected by this parameter. Any filtering as a result of "active" status
517 // in the external table itself is always applied. I am implementing the behavior
518 // just as was done prior to the refactor
519 // - Kevin Yeh
520 // If there is no entry in codes sql table, then default to active
521 // (this is reason for including NULL below)
522 if ($table_id == 0) {
523 // Search from default codes table
524 $active_query = " AND codes.active = 1 ";
525 } else {
526 // Search from external tables
527 $active_query = " AND (codes.active = 1 || codes.active IS NULL) ";
531 // Get/set the basic metadata information
532 $table_info = $code_external_tables[$table_id];
533 $table = $table_info[EXT_TABLE_NAME];
534 $table_dot = $table . ".";
535 $code_col = $table_info[EXT_COL_CODE];
536 $code_text_col = $table_info[EXT_COL_DESCRIPTION];
537 $code_text_short_col = $table_info[EXT_COL_DESCRIPTION_BRIEF];
538 if ($table_id == 0) {
539 $table_info[EXT_FILTER_CLAUSES] = array("code_type=" . $code_types[$form_code_type]['id']); // Add a filter for the code type
542 $code_external = $code_types[$form_code_type]['external'];
544 // If the description is supposed to come from "joined" table instead of the "main",
545 // the metadata defines a DISPLAY_DESCRIPTION element, and we use that to build up the query
546 if ($table_info[DISPLAY_DESCRIPTION] != "") {
547 $display_description = $table_info[DISPLAY_DESCRIPTION];
548 $display_description_brief = $table_info[DISPLAY_DESCRIPTION];
549 } else {
550 $display_description = $table_dot . $code_text_col;
551 $display_description_brief = $table_dot . $code_text_short_col;
554 // Ensure the external table exists
555 $check_table = sqlQuery("SHOW TABLES LIKE '" . $table . "'");
556 if ((empty($check_table))) {
557 HelpfulDie("Missing table in code set search:" . $table);
560 $sql_bind_array = array();
561 if ($count) {
562 // only collecting a count
563 $query = "SELECT count(" . $table_dot . $code_col . ") as count ";
564 } else {
565 $query = "SELECT '" . $code_external . "' as code_external, " .
566 $table_dot . $code_col . " as code, " .
567 $display_description . " as code_text, " .
568 $display_description_brief . " as code_text_short, " .
569 $columns . " ";
572 if ($table_id == 0) {
573 // Search from default codes table
574 $query .= " FROM " . $table . " ";
575 } else {
576 // Search from external tables
577 $query .= " FROM " . $table .
578 " LEFT OUTER JOIN `codes` " .
579 " ON " . $table_dot . $code_col . " = codes.code AND codes.code_type = ? ";
580 array_push($sql_bind_array, $code_types[$form_code_type]['id']);
583 foreach ($table_info[EXT_JOINS] as $join_info) {
584 $join_table = $join_info[JOIN_TABLE];
585 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
586 if ((empty($check_table))) {
587 HelpfulDie("Missing join table in code set search:" . $join_table);
590 $query .= " INNER JOIN " . $join_table;
591 $query .= " ON ";
592 $not_first = false;
593 foreach ($join_info[JOIN_FIELDS] as $field) {
594 if ($not_first) {
595 $query .= " AND ";
598 $query .= $field;
599 $not_first = true;
603 // Setup the where clause based on MODE
604 $query .= " WHERE ";
605 if ($return_only_one) {
606 $query .= $table_dot . $code_col . " = ? ";
607 array_push($sql_bind_array, $search_term);
608 } elseif ($mode == "code") {
609 $query .= $table_dot . $code_col . " like ? ";
610 array_push($sql_bind_array, $search_term . "%");
611 } elseif ($mode == "description") {
612 $description_keywords = preg_split("/ /", $search_term, -1, PREG_SPLIT_NO_EMPTY);
613 $query .= "(1=1 ";
614 foreach ($description_keywords as $keyword) {
615 $query .= " AND " . $table_dot . $code_text_col . " LIKE ? ";
616 array_push($sql_bind_array, "%" . $keyword . "%");
619 $query .= ")";
620 } else { // $mode == "default"
621 $query .= "(" . $table_dot . $code_text_col . " LIKE ? OR " . $table_dot . $code_col . " LIKE ?) ";
622 array_push($sql_bind_array, "%" . $search_term . "%", "%" . $search_term . "%");
625 // Done setting up the where clause by mode
627 // Add the metadata related filter clauses
628 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
629 $query .= " AND ";
630 $dot_location = strpos($filter_clause, ".");
631 if ($dot_location !== false) {
632 // The filter clause already includes a table specifier, so don't add one
633 $query .= $filter_clause;
634 } else {
635 $query .= $table_dot . $filter_clause;
639 $query .= $active_query . $query_filter_elements;
641 $query .= " ORDER BY " . $table_dot . $code_col . "+0," . $table_dot . $code_col;
643 if ($return_query) {
644 // Just returning the actual query without the LIMIT information in it. This
645 // information can then be used to combine queries of different code types
646 // via the mysql UNION command. Returning an array to contain the query string
647 // and the binding parameters.
648 return array('query' => $query,'binds' => $sql_bind_array);
651 $query .= $limit_query;
653 $res = sqlStatement($query, $sql_bind_array);
654 } else {
655 HelpfulDie("Code type not active or not defined:" . $join_info[JOIN_TABLE]);
657 } // End specific code type search
659 if (isset($res)) {
660 if ($count) {
661 // just return the count
662 $ret = sqlFetchArray($res);
663 return $ret['count'];
664 } else {
665 // return the data
666 return $res;
672 * Lookup Code Descriptions for one or more billing codes.
674 * Function is able to lookup code descriptions from a variety of code sets. See the 'external'
675 * items in the comments at top of this page for a listing of the code sets supported.
677 * @param string $codes Is of the form "type:code;type:code; etc.".
678 * @param string $desc_detail Can choose either the normal description('code_text') or the brief description('code_text_short').
679 * @return string Is of the form "description;description; etc.".
681 function lookup_code_descriptions($codes, $desc_detail = "code_text")
683 global $code_types, $code_external_tables;
685 // ensure $desc_detail is set properly
686 if (($desc_detail != "code_text") && ($desc_detail != "code_text_short")) {
687 $desc_detail = "code_text";
690 $code_text = '';
691 if (!empty($codes)) {
692 $relcodes = explode(';', $codes);
693 foreach ($relcodes as $codestring) {
694 if ($codestring === '') {
695 continue;
698 // added $modifier for HCPCS and other internal codesets so can grab exact entry in codes table
699 $code_parts = explode(':', $codestring);
700 $codetype = $code_parts[0] ?? null;
701 $code = $code_parts[1] ?? null;
702 $modifier = $code_parts[2] ?? null;
703 // if we don't have the code types we can't do much here
704 if (!isset($code_types[$codetype])) {
705 // we can't do much so we will just continue here...
706 continue;
709 $table_id = $code_types[$codetype]['external'] ?? '';
710 if (!isset($code_external_tables[$table_id])) {
711 //using an external code that is not yet supported, so skip.
712 continue;
715 $table_info = $code_external_tables[$table_id];
716 $table_name = $table_info[EXT_TABLE_NAME];
717 $code_col = $table_info[EXT_COL_CODE];
718 $desc_col = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION] : $table_info[DISPLAY_DESCRIPTION];
719 $desc_col_short = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION_BRIEF] : $table_info[DISPLAY_DESCRIPTION];
720 $sqlArray = array();
721 $sql = "SELECT " . $desc_col . " as code_text," . $desc_col_short . " as code_text_short FROM " . $table_name;
723 // include the "JOINS" so that we get the preferred term instead of the FullySpecifiedName when appropriate.
724 foreach ($table_info[EXT_JOINS] as $join_info) {
725 $join_table = $join_info[JOIN_TABLE];
726 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
727 if ((empty($check_table))) {
728 HelpfulDie("Missing join table in code set search:" . $join_table);
731 $sql .= " INNER JOIN " . $join_table;
732 $sql .= " ON ";
733 $not_first = false;
734 foreach ($join_info[JOIN_FIELDS] as $field) {
735 if ($not_first) {
736 $sql .= " AND ";
739 $sql .= $field;
740 $not_first = true;
744 $sql .= " WHERE ";
747 // Start building up the WHERE clause
749 // When using the external codes table, we have to filter by the code_type. (All the other tables only contain one type)
750 if ($table_id == 0) {
751 $sql .= " code_type = '" . add_escape_custom($code_types[$codetype]['id']) . "' AND ";
754 // Specify the code in the query.
755 $sql .= $table_name . "." . $code_col . "=? ";
756 array_push($sqlArray, $code);
758 // Add the modifier if necessary for CPT and HCPCS which differentiates code
759 if ($modifier) {
760 $sql .= " AND modifier = ? ";
761 array_push($sqlArray, $modifier);
764 // We need to include the filter clauses
765 // For SNOMED and SNOMED-CT this ensures that we get the Preferred Term or the Fully Specified Term as appropriate
766 // It also prevents returning "inactive" results
767 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
768 $sql .= " AND " . $filter_clause;
771 // END building the WHERE CLAUSE
774 if ($table_info[EXT_VERSION_ORDER]) {
775 $sql .= " ORDER BY " . $table_info[EXT_VERSION_ORDER];
778 $sql .= " LIMIT 1";
779 $crow = sqlQuery($sql, $sqlArray);
780 if (!empty($crow[$desc_detail])) {
781 if ($code_text) {
782 $code_text .= '; ';
785 $code_text .= $crow[$desc_detail];
790 return $code_text;
794 * Sequential code set "internal" searching function
796 * Function is basically a wrapper of the code_set_search() function to support
797 * a optimized searching models. The default mode will:
798 * Searches codes first; then if no hits, it will then search the descriptions
799 * (which are separated by each word in the code_set_search() function).
800 * (This function is not meant to be called directly)
802 * @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)
803 * @param string $search_term search term
804 * @param integer $limit Number of results to return (NULL means return all)
805 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
806 * @param boolean $count if true, then will only return the number of entries
807 * @param boolean $active if true, then will only return active entries
808 * @param integer $start Query start limit (for pagination)
809 * @param integer $number Query number returned (for pagination)
810 * @param array $filter_elements Array that contains elements to filter
811 * @param string $is_hit_mode This is a mode that simply returns the name of the mode if results were found
812 * @return recordset/integer/string
814 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)
816 // Set the default behavior that is described in above function comments
817 if (empty($modes)) {
818 $modes = array('code','description');
821 // Return the Search Results (loop through each mode in order)
822 foreach ($modes as $mode) {
823 $res = code_set_search($form_code_type, $search_term, $count, $active, false, $start, $number, $filter_elements, $limit, $mode);
824 if (($count && $res > 0) || (!$count && sqlNumRows($res) > 0)) {
825 if ($is_hit_mode) {
826 // just return the mode
827 return $mode;
828 } else {
829 // returns the count number if count is true or returns the data if count is false
830 return $res;
837 * Code set searching "internal" function for when searching multiple code sets.
839 * It will also work for one code set search, although not meant for this.
840 * (This function is not meant to be called directly)
842 * @param array $form_code_types code set keys (will default to checking all active code types if blank)
843 * @param string $search_term search term
844 * @param integer $limit Number of results to return (NULL means return all)
845 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
846 * @param boolean $count if true, then will only return the number of entries
847 * @param boolean $active if true, then will only return active entries
848 * @param integer $start Query start limit (for pagination)
849 * @param integer $number Query number returned (for pagination)
850 * @param array $filter_elements Array that contains elements to filter
851 * @return recordset/integer
853 function multiple_code_set_search(array $form_code_types = null, $search_term, $limit = null, $modes = null, $count = false, $active = true, $start = null, $number = null, $filter_elements = array())
856 if (empty($form_code_types)) {
857 // Collect the active code types
858 $form_code_types = collect_codetypes("active", "array");
861 if ($count) {
862 //start the counter
863 $counter = 0;
864 } else {
865 // Figure out the appropriate limit clause
866 $limit_query = limit_query_string($limit, $start, $number);
868 // Prepare the sql bind array
869 $sql_bind_array = array();
871 // Start the query string
872 $query = "SELECT * FROM ((";
875 // Loop through each code type
876 $flag_first = true;
877 $flag_hit = false; //ensure there is a hit to avoid trying an empty query
878 foreach ($form_code_types as $form_code_type) {
879 // see if there is a hit
880 $mode_hit = null;
881 // only use the count method here, since it's much more efficient than doing the actual query
882 $mode_hit = sequential_code_set_search($form_code_type, $search_term, null, $modes, true, $active, null, null, $filter_elements, true);
883 if ($mode_hit) {
884 if ($count) {
885 // count the hits
886 $count_hits = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit);
887 // increment the counter
888 $counter += $count_hits;
889 } else {
890 $flag_hit = true;
891 // build the query
892 $return_query = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit, true);
893 if (!empty($sql_bind_array)) {
894 $sql_bind_array = array_merge($sql_bind_array, $return_query['binds']);
895 } else {
896 $sql_bind_array = $return_query['binds'];
899 if (!$flag_first) {
900 $query .= ") UNION ALL (";
903 $query .= $return_query['query'];
906 $flag_first = false;
910 if ($count) {
911 //return the count
912 return $counter;
913 } else {
914 // Finish the query string
915 $query .= ")) as atari $limit_query";
917 // Process and return the query (if there was a hit)
918 if ($flag_hit) {
919 return sqlStatement($query, $sql_bind_array);
925 * Returns the limit to be used in the sql query for code set searches.
927 * @param integer $limit Number of results to return (NULL means return all)
928 * @param integer $start Query start limit (for pagination)
929 * @param integer $number Query number returned (for pagination)
930 * @param boolean $return_only_one if true, then will only return one perfect matching item
931 * @return recordset/integer
933 function limit_query_string($limit = null, $start = null, $number = null, $return_only_one = false)
935 if (!is_null($start) && !is_null($number)) {
936 // For pagination of results
937 $limit_query = " LIMIT " . escape_limit($start) . ", " . escape_limit($number) . " ";
938 } elseif (!is_null($limit)) {
939 $limit_query = " LIMIT " . escape_limit($limit) . " ";
940 } else {
941 // No pagination and no limit
942 $limit_query = '';
945 if ($return_only_one) {
946 // Only return one result (this is where only matching for exact code match)
947 // Note this overrides the above limit settings
948 $limit_query = " LIMIT 1 ";
951 return $limit_query;
954 // Recursive function to look up the IPPF2 (or other type) code, if any,
955 // for a given related code field.
957 function recursive_related_code($related_code, $typewanted = 'IPPF2', $depth = 0)
959 global $code_types;
960 // echo "<!-- related_code = '$related_code' depth = '$depth' -->\n"; // debugging
961 if (++$depth > 4 || empty($related_code)) {
962 return false; // protects against relation loops
964 $relcodes = explode(';', $related_code);
965 foreach ($relcodes as $codestring) {
966 if ($codestring === '') {
967 continue;
969 list($codetype, $code) = explode(':', $codestring);
970 if ($codetype === $typewanted) {
971 // echo "<!-- returning '$code' -->\n"; // debugging
972 return $code;
974 $row = sqlQuery(
975 "SELECT related_code FROM codes WHERE " .
976 "code_type = ? AND code = ? AND active = 1 " .
977 "ORDER BY id LIMIT 1",
978 array($code_types[$codetype]['id'], $code)
980 $tmp = recursive_related_code($row['related_code'], $typewanted, $depth);
981 if ($tmp !== false) {
982 return $tmp;
985 return false;