improved prior 8.2 fix
[openemr.git] / custom / code_types.inc.php
blobc7a5aa975e6a9eaa686e4cea2f17ba91a956a58b
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 * @author Jerry Padgett <sjpadgett@gmail.com>
48 * @copyright Copyright (c) 2006-2010 Rod Roark <rod@sunsetsystems.com>
49 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
50 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
53 require_once(__DIR__ . "/../library/csv_like_join.php");
55 $code_types = array();
56 global $code_types;
57 $ctres = sqlStatement("SELECT * FROM code_types WHERE ct_active=1 ORDER BY ct_seq, ct_key");
58 while ($ctrow = sqlFetchArray($ctres)) {
59 $code_types[$ctrow['ct_key']] = array(
60 'active' => $ctrow['ct_active' ],
61 'id' => $ctrow['ct_id' ],
62 'fee' => $ctrow['ct_fee' ],
63 'mod' => $ctrow['ct_mod' ],
64 'just' => $ctrow['ct_just'],
65 'rel' => $ctrow['ct_rel' ],
66 'nofs' => $ctrow['ct_nofs'],
67 'diag' => $ctrow['ct_diag'],
68 'mask' => $ctrow['ct_mask'],
69 'label' => ( (empty($ctrow['ct_label'])) ? $ctrow['ct_key'] : $ctrow['ct_label'] ),
70 'external' => $ctrow['ct_external'],
71 'claim' => $ctrow['ct_claim'],
72 'proc' => $ctrow['ct_proc'],
73 'term' => $ctrow['ct_term'],
74 'problem' => $ctrow['ct_problem'],
75 'drug' => $ctrow['ct_drug']
77 if (!array_key_exists($GLOBALS['default_search_code_type'], $code_types)) {
78 reset($code_types);
79 $GLOBALS['default_search_code_type'] = key($code_types);
83 /** This array contains metadata describing the arrangement of the external data
84 * tables for storing codes.
86 $code_external_tables = array();
87 global $code_external_tables;
88 define('EXT_COL_CODE', 'code');
89 define('EXT_COL_DESCRIPTION', 'description');
90 define('EXT_COL_DESCRIPTION_BRIEF', 'description_brief');
91 define('EXT_TABLE_NAME', 'table');
92 define('EXT_FILTER_CLAUSES', 'filter_clause');
93 define('EXT_VERSION_ORDER', 'filter_version_order');
94 define('EXT_JOINS', 'joins');
95 define('JOIN_TABLE', 'join');
96 define('JOIN_FIELDS', 'fields');
97 define('DISPLAY_DESCRIPTION', "display_description");
99 /**
100 * This is a helper function for defining the metadata that describes the tables
102 * @param type $results A reference to the global array which stores all the metadata
103 * @param type $index The external table ID. This corresponds to the value in the code_types table in the ct_external column
104 * @param type $table_name The name of the table which stores the code informattion (e.g. icd9_dx_code
105 * @param type $col_code The name of the column which is the code
106 * @param type $col_description The name of the column which is the description
107 * @param type $col_description_brief The name of the column which is the brief description
108 * @param type $filter_clauses An array of clauses to be included in the search "WHERE" clause that limits results
109 * @param type $version_order How to choose between different revisions of codes
110 * @param type $joins An array which describes additional tables to join as part of a code search.
112 function define_external_table(&$results, $index, $table_name, $col_code, $col_description, $col_description_brief, $filter_clauses = array(), $version_order = "", $joins = array(), $display_desc = "")
114 $results[$index] = array(EXT_TABLE_NAME => $table_name,
115 EXT_COL_CODE => $col_code,
116 EXT_COL_DESCRIPTION => $col_description,
117 EXT_COL_DESCRIPTION_BRIEF => $col_description_brief,
118 EXT_FILTER_CLAUSES => $filter_clauses,
119 EXT_JOINS => $joins,
120 EXT_VERSION_ORDER => $version_order,
121 DISPLAY_DESCRIPTION => $display_desc
124 // In order to treat all the code types the same for lookup_code_descriptions, we include metadata for the original codes table
125 define_external_table($code_external_tables, 0, 'codes', 'code', 'code_text', 'code_text_short', array(), 'id');
127 // ICD9 External Definitions
128 define_external_table($code_external_tables, 4, 'icd9_dx_code', 'formatted_dx_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
129 define_external_table($code_external_tables, 5, 'icd9_sg_code', 'formatted_sg_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
130 //**** End ICD9 External Definitions
132 // SNOMED Definitions
133 // For generic SNOMED-CT, there is no need to join with the descriptions table to get a specific description Type
135 // For generic concepts, use the fully specified description (DescriptionType=3) so we can tell the difference between them.
136 define_external_table($code_external_tables, 7, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=3"), "");
138 // To determine codes, we need to evaluate data in both the sct_descriptions table, and the sct_concepts table.
139 // the base join with sct_concepts is the same for all types of SNOMED definitions, so we define the common part here
140 $SNOMED_joins = array(JOIN_TABLE => "sct_concepts",JOIN_FIELDS => array("sct_descriptions.ConceptId=sct_concepts.ConceptId"));
142 // For disorders, use the preferred term (DescriptionType=1)
143 define_external_table($code_external_tables, 2, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=1"), "", array($SNOMED_joins));
144 // Add the filter to choose only disorders. This filter happens as part of the join with the sct_concepts table
145 array_push($code_external_tables[2][EXT_JOINS][0][JOIN_FIELDS], "FullySpecifiedName like '%(disorder)'");
147 // SNOMED-PR definition
148 define_external_table($code_external_tables, 9, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=1"), "", array($SNOMED_joins));
149 // Add the filter to choose only procedures. This filter happens as part of the join with the sct_concepts table
150 array_push($code_external_tables[9][EXT_JOINS][0][JOIN_FIELDS], "FullySpecifiedName like '%(procedure)'");
152 // SNOMED RF2 definitions
153 define_external_table($code_external_tables, 11, 'sct2_description', 'conceptId', 'term', 'term', array("active=1"), "");
154 if (isSnomedSpanish()) {
155 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(trastorno)'"), "");
156 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedimiento)'"), "");
157 } else {
158 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(disorder)'"), "");
159 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedure)'"), "");
162 //**** End SNOMED Definitions
164 // ICD 10 Definitions
165 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');
166 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');
167 //**** End ICD 10 Definitions
169 define_external_table($code_external_tables, 13, 'valueset', 'code', 'description', 'description', array(), '');
172 * This array stores the external table options. See above for $code_types array
173 * 'external' attribute for explanation of the option listings.
174 * @var array
176 global $ct_external_options;
177 $ct_external_options = array(
178 '0' => xl('No'),
179 '4' => xl('ICD9 Diagnosis'),
180 '5' => xl('ICD9 Procedure/Service'),
181 '1' => xl('ICD10 Diagnosis'),
182 '6' => xl('ICD10 Procedure/Service'),
183 '2' => xl('SNOMED (RF1) Diagnosis'),
184 '7' => xl('SNOMED (RF1) Clinical Term'),
185 '9' => xl('SNOMED (RF1) Procedure'),
186 '10' => xl('SNOMED (RF2) Diagnosis'),
187 '11' => xl('SNOMED (RF2) Clinical Term'),
188 '12' => xl('SNOMED (RF2) Procedure'),
189 '13' => xl('CQM (Mixed Types) Value Set')
193 * Checks to see if using spanish snomed
195 function isSnomedSpanish()
197 // See if most recent SNOMED entry is International:Spanish
198 $sql = sqlQuery("SELECT `revision_version` FROM `standardized_tables_track` WHERE `name` = 'SNOMED' ORDER BY `id` DESC");
199 if ((!empty($sql)) && ($sql['revision_version'] == "International:Spanish")) {
200 return true;
202 return false;
206 * Checks is fee are applicable to any of the code types.
208 * @return boolean
210 function fees_are_used()
212 global $code_types;
213 foreach ($code_types as $value) {
214 if ($value['fee'] && $value['active']) {
215 return true;
219 return false;
223 * Checks if modifiers are applicable to any of the code types.
224 * (If a code type is not set to show in the fee sheet, then is ignored)
226 * @param boolean $fee_sheet Will ignore code types that are not shown in the fee sheet
227 * @return boolean
229 function modifiers_are_used($fee_sheet = false)
231 global $code_types;
232 foreach ($code_types as $value) {
233 if ($fee_sheet && !empty($value['nofs'])) {
234 continue;
237 if ($value['mod'] && $value['active']) {
238 return true;
242 return false;
246 * Checks if justifiers are applicable to any of the code types.
248 * @return boolean
250 function justifiers_are_used()
252 global $code_types;
253 foreach ($code_types as $value) {
254 if (!empty($value['just']) && $value['active']) {
255 return true;
259 return false;
263 * Checks is related codes are applicable to any of the code types.
265 * @return boolean
267 function related_codes_are_used()
269 global $code_types;
270 foreach ($code_types as $value) {
271 if ($value['rel'] && $value['active']) {
272 return true;
276 return false;
280 * Convert a code type id (ct_id) to the key string (ct_key)
282 * @param integer $id
283 * @return string
285 function convert_type_id_to_key($id)
287 global $code_types;
288 foreach ($code_types as $key => $value) {
289 if ($value['id'] == $id) {
290 return $key;
296 * Checks to see if code allows justification (ct_just)
298 * @param string $key
299 * @return boolean
301 function check_is_code_type_justify($key)
303 global $code_types;
305 if (!empty($code_types[$key]['just'])) {
306 return true;
307 } else {
308 return false;
313 * Checks if a key string (ct_key) is selected for an element/filter(s)
315 * @param string $key
316 * @param array $filter (array of elements that can include 'active','fee','rel','nofs','diag','claim','proc','term','problem')
317 * @return boolean
319 function check_code_set_filters($key, $filters = array())
321 global $code_types;
323 if (empty($filters)) {
324 return false;
327 foreach ($filters as $filter) {
328 if (array_key_exists($key, $code_types)) {
329 if ($code_types[$key][$filter] != 1) {
330 return false;
335 // Filter was passed
336 return true;
340 * Return listing of pertinent and active code types.
342 * Function will return listing (ct_key) of pertinent
343 * active code types, such as diagnosis codes or procedure
344 * codes in a chosen format. Supported returned formats include
345 * as 1) an array and as 2) a comma-separated lists that has been
346 * process by urlencode() in order to place into URL address safely.
348 * @param string $category category of code types('diagnosis', 'procedure', 'clinical_term', 'active' or 'medical_problem')
349 * @param string $return_format format or returned code types ('array' or 'csv')
350 * @return string/array
352 function collect_codetypes($category, $return_format = "array")
354 global $code_types;
356 $return = array();
358 foreach ($code_types as $ct_key => $ct_arr) {
359 if (!$ct_arr['active']) {
360 continue;
363 if ($category == "diagnosis") {
364 if ($ct_arr['diag']) {
365 $return[] = $ct_key;
367 } elseif ($category == "procedure") {
368 if ($ct_arr['proc']) {
369 $return[] = $ct_key;
371 } elseif ($category == "clinical_term") {
372 if ($ct_arr['term']) {
373 $return[] = $ct_key;
375 } elseif ($category == "active") {
376 if ($ct_arr['active']) {
377 $return[] = $ct_key;
379 } elseif ($category == "medical_problem") {
380 if ($ct_arr['problem']) {
381 $return[] = $ct_key;
383 } elseif ($category == "drug") {
384 if ($ct_arr['drug']) {
385 $return[] = $ct_key;
387 } else {
388 //return nothing since no supported category was chosen
392 if ($return_format == "csv") {
393 //return it as a csv string
394 return csv_like_join($return);
397 //$return_format == "array"
398 //return the array
399 return $return;
403 * Return the code information for a specific code.
405 * Function is able to search a variety of code sets. See the code type items in the comments at top
406 * of this page for a listing of the code sets supported.
408 * @param string $form_code_type code set key
409 * @param string $code code
410 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
411 * @return mixed recordset - will contain only one item (row).
413 function return_code_information($form_code_type, $code, $active = true)
415 return code_set_search($form_code_type, $code, false, $active, true);
419 * The main code set searching function.
421 * It will work for searching one or numerous code sets simultaneously.
422 * Note that when searching numerous code sets, you CAN NOT search the PROD
423 * codes; the PROD codes can only be searched by itself.
425 * @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
426 * @param string $search_term search term
427 * @param integer $limit Number of results to return (NULL means return all)
428 * @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)
429 * @param boolean $active if true, then will only return active entries
430 * @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)
431 * @param boolean $count if true, then will only return the number of entries
432 * @param integer $start Query start limit (for pagination) (Note this setting will override the above $limit parameter)
433 * @param integer $number Query number returned (for pagination) (Note this setting will override the above $limit parameter)
434 * @param array $filter_elements Array that contains elements to filter
435 * @return mixed recordset/integer - Will contain either a integer(if counting) or the results (recordset)
437 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())
440 // check for a category
441 if (!empty($category)) {
442 $form_code_type = collect_codetypes($category, "array");
445 // do the search
446 if (!empty($form_code_type)) {
447 if (is_array($form_code_type) && (count($form_code_type) > 1)) {
448 // run the multiple code set search
449 return multiple_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
452 if (is_array($form_code_type) && (count($form_code_type) == 1)) {
453 // prepare the variable (ie. convert the one array item to a string) for the non-multiple code set search
454 $form_code_type = $form_code_type[0];
457 // run the non-multiple code set search
458 return sequential_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
463 * Main "internal" code set searching function.
465 * Function is able to search a variety of code sets. See the 'external' items in the comments at top
466 * of this page for a listing of the code sets supported. Also note that Products (using PROD as code type)
467 * is also supported. (This function is not meant to be called directly)
469 * @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)
470 * @param string $search_term search term
471 * @param boolean $count if true, then will only return the number of entries
472 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
473 * @param boolean $return_only_one if true, then will only return one perfect matching item
474 * @param integer $start Query start limit
475 * @param integer $number Query number returned
476 * @param array $filter_elements Array that contains elements to filter
477 * @param integer $limit Number of results to return (NULL means return all); note this is ignored if set $start/number
478 * @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
479 * @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)
480 * @return mixed recordset/integer/array
482 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)
484 global $code_types, $code_external_tables;
486 // Figure out the appropriate limit clause
487 $limit_query = limit_query_string($limit, $start, $number, $return_only_one);
489 // build the filter_elements sql code
490 $query_filter_elements = "";
491 if (!empty($filter_elements)) {
492 foreach ($filter_elements as $key => $element) {
493 $query_filter_elements .= " AND codes." . add_escape_custom($key) . "=" . "'" . add_escape_custom($element) . "' ";
497 if ($form_code_type == 'PROD') { // Search for products/drugs
498 if ($count) {
499 $query = "SELECT count(dt.drug_id) as count ";
500 } else {
501 $query = "SELECT dt.drug_id, dt.selector, d.name ";
504 $query .= "FROM drug_templates AS dt, drugs AS d WHERE " .
505 "( d.name LIKE ? OR " .
506 "dt.selector LIKE ? ) " .
507 "AND d.drug_id = dt.drug_id " .
508 "ORDER BY d.name, dt.selector, dt.drug_id $limit_query";
509 $res = sqlStatement($query, array("%" . $search_term . "%", "%" . $search_term . "%"));
510 } else { // Start a codes search
511 // 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.
512 $table_id = isset($code_types[$form_code_type]['external']) ? intval(($code_types[$form_code_type]['external'])) : -9999 ;
513 if ($table_id >= 0) { // We found a definition for the given code search, so start building the query
514 // Place the common columns variable here since all check codes table
515 $common_columns = " codes.id, codes.code_type, codes.modifier, codes.units, codes.fee, " .
516 "codes.superbill, codes.related_code, codes.taxrates, codes.cyp_factor, " .
517 "codes.active, codes.reportable, codes.financial_reporting, codes.revenue_code, ";
518 $columns = $common_columns . "'" . add_escape_custom($form_code_type) . "' as code_type_name ";
520 $active_query = '';
521 if ($active) {
522 // Only filter for active codes. Only the active column in the joined table
523 // is affected by this parameter. Any filtering as a result of "active" status
524 // in the external table itself is always applied. I am implementing the behavior
525 // just as was done prior to the refactor
526 // - Kevin Yeh
527 // If there is no entry in codes sql table, then default to active
528 // (this is reason for including NULL below)
529 if ($table_id == 0) {
530 // Search from default codes table
531 $active_query = " AND codes.active = 1 ";
532 } else {
533 // Search from external tables
534 $active_query = " AND (codes.active = 1 || codes.active IS NULL) ";
538 // Get/set the basic metadata information
539 $table_info = $code_external_tables[$table_id];
540 $table = $table_info[EXT_TABLE_NAME];
541 $table_dot = $table . ".";
542 $code_col = $table_info[EXT_COL_CODE];
543 $code_text_col = $table_info[EXT_COL_DESCRIPTION];
544 $code_text_short_col = $table_info[EXT_COL_DESCRIPTION_BRIEF];
545 if ($table_id == 0) {
546 $table_info[EXT_FILTER_CLAUSES] = array("code_type=" . $code_types[$form_code_type]['id']); // Add a filter for the code type
549 $code_external = $code_types[$form_code_type]['external'];
551 // If the description is supposed to come from "joined" table instead of the "main",
552 // the metadata defines a DISPLAY_DESCRIPTION element, and we use that to build up the query
553 if ($table_info[DISPLAY_DESCRIPTION] != "") {
554 $display_description = $table_info[DISPLAY_DESCRIPTION];
555 $display_description_brief = $table_info[DISPLAY_DESCRIPTION];
556 } else {
557 $display_description = $table_dot . $code_text_col;
558 $display_description_brief = $table_dot . $code_text_short_col;
561 // Ensure the external table exists
562 $check_table = sqlQuery("SHOW TABLES LIKE '" . $table . "'");
563 if ((empty($check_table))) {
564 HelpfulDie("Missing table in code set search:" . $table);
567 $sql_bind_array = array();
568 if ($count) {
569 // only collecting a count
570 $query = "SELECT count(" . $table_dot . $code_col . ") as count ";
571 } else {
572 $substitute = '';
573 if ($table_dot === 'valueset.') {
574 $substitute = 'valueset.code_type as valueset_code_type, ';
576 $query = "SELECT '" . $code_external . "' as code_external, " .
577 $table_dot . $code_col . " as code, " .
578 $display_description . " as code_text, " .
579 $display_description_brief . " as code_text_short, " .
580 $substitute . $columns . " ";
583 if ($table_id == 0) {
584 // Search from default codes table
585 $query .= " FROM " . $table . " ";
586 } else {
587 // Search from external tables
588 $query .= " FROM " . $table .
589 " LEFT OUTER JOIN `codes` " .
590 " ON " . $table_dot . $code_col . " = codes.code AND codes.code_type = ? ";
591 $sql_bind_array[] = $code_types[$form_code_type]['id'];
594 foreach ($table_info[EXT_JOINS] as $join_info) {
595 $join_table = $join_info[JOIN_TABLE];
596 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
597 if ((empty($check_table))) {
598 HelpfulDie("Missing join table in code set search:" . $join_table);
601 $query .= " INNER JOIN " . $join_table;
602 $query .= " ON ";
603 $not_first = false;
604 foreach ($join_info[JOIN_FIELDS] as $field) {
605 if ($not_first) {
606 $query .= " AND ";
609 $query .= $field;
610 $not_first = true;
614 // Setup the where clause based on MODE
615 $query .= " WHERE ";
616 if ($return_only_one) {
617 $query .= $table_dot . $code_col . " = ? ";
618 $sql_bind_array[] = $search_term;
619 } elseif ($mode == "code") {
620 $query .= $table_dot . $code_col . " like ? ";
621 $sql_bind_array[] = $search_term . "%";
622 } elseif ($mode == "description") {
623 $description_keywords = preg_split("/ /", $search_term, -1, PREG_SPLIT_NO_EMPTY);
624 $query .= "(1=1 ";
625 foreach ($description_keywords as $keyword) {
626 $query .= " AND " . $table_dot . $code_text_col . " LIKE ? ";
627 $sql_bind_array[] = "%" . $keyword . "%";
630 $query .= ")";
631 } else { // $mode == "default"
632 $query .= "(" . $table_dot . $code_text_col . " LIKE ? OR " . $table_dot . $code_col . " LIKE ?) ";
633 array_push($sql_bind_array, "%" . $search_term . "%", "%" . $search_term . "%");
636 // Done setting up the where clause by mode
638 // Add the metadata related filter clauses
639 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
640 $query .= " AND ";
641 $dot_location = strpos($filter_clause, ".");
642 if ($dot_location !== false) {
643 // The filter clause already includes a table specifier, so don't add one
644 $query .= $filter_clause;
645 } else {
646 $query .= $table_dot . $filter_clause;
650 $query .= $active_query . $query_filter_elements;
652 $query .= " ORDER BY " . $table_dot . $code_col . "+0," . $table_dot . $code_col;
654 if ($return_query) {
655 // Just returning the actual query without the LIMIT information in it. This
656 // information can then be used to combine queries of different code types
657 // via the mysql UNION command. Returning an array to contain the query string
658 // and the binding parameters.
659 return array('query' => $query,'binds' => $sql_bind_array);
662 $query .= $limit_query;
664 $res = sqlStatement($query, $sql_bind_array);
665 } else {
666 HelpfulDie("Code type not active or not defined:" . $join_info[JOIN_TABLE]);
668 } // End specific code type search
670 if (isset($res)) {
671 if ($count) {
672 // just return the count
673 $ret = sqlFetchArray($res);
674 return $ret['count'];
676 // return the data
677 return $res;
682 * Lookup Code Descriptions for one or more billing codes.
684 * Function is able to lookup code descriptions from a variety of code sets. See the 'external'
685 * items in the comments at top of this page for a listing of the code sets supported.
687 * @param string $codes Is of the form "type:code;type:code; etc.".
688 * @param string $desc_detail Can choose either the normal description('code_text') or the brief description('code_text_short').
689 * @return string Is of the form "description;description; etc.".
691 function lookup_code_descriptions($codes, $desc_detail = "code_text")
693 global $code_types, $code_external_tables;
695 // ensure $desc_detail is set properly
696 if (($desc_detail != "code_text") && ($desc_detail != "code_text_short")) {
697 $desc_detail = "code_text";
700 $code_text = '';
701 if (!empty($codes)) {
702 $relcodes = explode(';', $codes);
703 foreach ($relcodes as $codestring) {
704 if ($codestring === '') {
705 continue;
708 // added $modifier for HCPCS and other internal codesets so can grab exact entry in codes table
709 $code_parts = explode(':', $codestring);
710 $codetype = $code_parts[0] ?? null;
711 $code = $code_parts[1] ?? null;
712 $modifier = $code_parts[2] ?? null;
713 // if we don't have the code types we can't do much here
714 if (!isset($code_types[$codetype])) {
715 // we can't do much so we will just continue here...
716 continue;
719 $table_id = $code_types[$codetype]['external'] ?? '';
720 if (!isset($code_external_tables[$table_id])) {
721 //using an external code that is not yet supported, so skip.
722 continue;
725 $table_info = $code_external_tables[$table_id];
726 $table_name = $table_info[EXT_TABLE_NAME];
727 $code_col = $table_info[EXT_COL_CODE];
728 $desc_col = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION] : $table_info[DISPLAY_DESCRIPTION];
729 $desc_col_short = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION_BRIEF] : $table_info[DISPLAY_DESCRIPTION];
730 $sqlArray = array();
731 $sql = "SELECT " . $desc_col . " as code_text," . $desc_col_short . " as code_text_short FROM " . $table_name;
733 // include the "JOINS" so that we get the preferred term instead of the FullySpecifiedName when appropriate.
734 foreach ($table_info[EXT_JOINS] as $join_info) {
735 $join_table = $join_info[JOIN_TABLE];
736 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
737 if ((empty($check_table))) {
738 HelpfulDie("Missing join table in code set search:" . $join_table);
741 $sql .= " INNER JOIN " . $join_table;
742 $sql .= " ON ";
743 $not_first = false;
744 foreach ($join_info[JOIN_FIELDS] as $field) {
745 if ($not_first) {
746 $sql .= " AND ";
749 $sql .= $field;
750 $not_first = true;
754 $sql .= " WHERE ";
757 // Start building up the WHERE clause
759 // When using the external codes table, we have to filter by the code_type. (All the other tables only contain one type)
760 if ($table_id == 0) {
761 $sql .= " code_type = '" . add_escape_custom($code_types[$codetype]['id']) . "' AND ";
764 // Specify the code in the query.
765 $sql .= $table_name . "." . $code_col . "=? ";
766 $sqlArray[] = $code;
768 // Add the modifier if necessary for CPT and HCPCS which differentiates code
769 if ($modifier) {
770 $sql .= " AND modifier = ? ";
771 $sqlArray[] = $modifier;
774 // We need to include the filter clauses
775 // For SNOMED and SNOMED-CT this ensures that we get the Preferred Term or the Fully Specified Term as appropriate
776 // It also prevents returning "inactive" results
777 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
778 $sql .= " AND " . $filter_clause;
781 // END building the WHERE CLAUSE
784 if ($table_info[EXT_VERSION_ORDER]) {
785 $sql .= " ORDER BY " . $table_info[EXT_VERSION_ORDER];
788 $sql .= " LIMIT 1";
789 $crow = sqlQuery($sql, $sqlArray);
790 if (!empty($crow[$desc_detail])) {
791 if ($code_text) {
792 $code_text .= '; ';
795 $code_text .= $crow[$desc_detail];
800 return $code_text;
804 * Sequential code set "internal" searching function
806 * Function is basically a wrapper of the code_set_search() function to support
807 * a optimized searching models. The default mode will:
808 * Searches codes first; then if no hits, it will then search the descriptions
809 * (which are separated by each word in the code_set_search() function).
810 * (This function is not meant to be called directly)
812 * @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)
813 * @param string $search_term search term
814 * @param integer $limit Number of results to return (NULL means return all)
815 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
816 * @param boolean $count if true, then will only return the number of entries
817 * @param boolean $active if true, then will only return active entries
818 * @param integer $start Query start limit (for pagination)
819 * @param integer $number Query number returned (for pagination)
820 * @param array $filter_elements Array that contains elements to filter
821 * @param string $is_hit_mode This is a mode that simply returns the name of the mode if results were found
822 * @return mixed recordset/integer/string
824 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)
826 // Set the default behavior that is described in above function comments
827 if (empty($modes)) {
828 $modes = array('code','description');
831 // Return the Search Results (loop through each mode in order)
832 foreach ($modes as $mode) {
833 $res = code_set_search($form_code_type, $search_term, $count, $active, false, $start, $number, $filter_elements, $limit, $mode);
834 if (($count && $res > 0) || (!$count && sqlNumRows($res) > 0)) {
835 if ($is_hit_mode) {
836 // just return the mode
837 return $mode;
838 } else {
839 // returns the count number if count is true or returns the data if count is false
840 return $res;
847 * Code set searching "internal" function for when searching multiple code sets.
849 * It will also work for one code set search, although not meant for this.
850 * (This function is not meant to be called directly)
852 * @param array $form_code_types code set keys (will default to checking all active code types if blank)
853 * @param string $search_term search term
854 * @param integer $limit Number of results to return (NULL means return all)
855 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
856 * @param boolean $count if true, then will only return the number of entries
857 * @param boolean $active if true, then will only return active entries
858 * @param integer $start Query start limit (for pagination)
859 * @param integer $number Query number returned (for pagination)
860 * @param array $filter_elements Array that contains elements to filter
861 * @return mixed recordset/integer
863 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())
866 if (empty($form_code_types)) {
867 // Collect the active code types
868 $form_code_types = collect_codetypes("active", "array");
871 if ($count) {
872 //start the counter
873 $counter = 0;
874 } else {
875 // Figure out the appropriate limit clause
876 $limit_query = limit_query_string($limit, $start, $number);
878 // Prepare the sql bind array
879 $sql_bind_array = array();
881 // Start the query string
882 $query = "SELECT * FROM ((";
885 // Loop through each code type
886 $flag_first = true;
887 $flag_hit = false; //ensure there is a hit to avoid trying an empty query
888 foreach ($form_code_types as $form_code_type) {
889 // see if there is a hit
890 $mode_hit = null;
891 // only use the count method here, since it's much more efficient than doing the actual query
892 $mode_hit = sequential_code_set_search($form_code_type, $search_term, null, $modes, true, $active, null, null, $filter_elements, true);
893 if ($mode_hit) {
894 if ($count) {
895 // count the hits
896 $count_hits = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit);
897 // increment the counter
898 $counter += $count_hits;
899 } else {
900 $flag_hit = true;
901 // build the query
902 $return_query = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit, true);
903 if (!empty($sql_bind_array)) {
904 $sql_bind_array = array_merge($sql_bind_array, $return_query['binds']);
905 } else {
906 $sql_bind_array = $return_query['binds'];
909 if (!$flag_first) {
910 $query .= ") UNION ALL (";
913 $query .= $return_query['query'];
916 $flag_first = false;
920 if ($count) {
921 //return the count
922 return $counter;
923 } else {
924 // Finish the query string
925 $query .= ")) as atari $limit_query";
927 // Process and return the query (if there was a hit)
928 if ($flag_hit) {
929 return sqlStatement($query, $sql_bind_array);
935 * Returns the limit to be used in the sql query for code set searches.
937 * @param integer $limit Number of results to return (NULL means return all)
938 * @param integer $start Query start limit (for pagination)
939 * @param integer $number Query number returned (for pagination)
940 * @param boolean $return_only_one if true, then will only return one perfect matching item
941 * @return mixed recordset/integer
943 function limit_query_string($limit = null, $start = null, $number = null, $return_only_one = false)
945 if (!is_null($start) && !is_null($number)) {
946 // For pagination of results
947 $limit_query = " LIMIT " . escape_limit($start) . ", " . escape_limit($number) . " ";
948 } elseif (!is_null($limit)) {
949 $limit_query = " LIMIT " . escape_limit($limit) . " ";
950 } else {
951 // No pagination and no limit
952 $limit_query = '';
955 if ($return_only_one) {
956 // Only return one result (this is where only matching for exact code match)
957 // Note this overrides the above limit settings
958 $limit_query = " LIMIT 1 ";
961 return $limit_query;
964 // Recursive function to look up the IPPF2 (or other type) code, if any,
965 // for a given related code field.
967 function recursive_related_code($related_code, $typewanted = 'IPPF2', $depth = 0)
969 global $code_types;
970 // echo "<!-- related_code = '$related_code' depth = '$depth' -->\n"; // debugging
971 if (++$depth > 4 || empty($related_code)) {
972 return false; // protects against relation loops
974 $relcodes = explode(';', $related_code);
975 foreach ($relcodes as $codestring) {
976 if ($codestring === '') {
977 continue;
979 list($codetype, $code) = explode(':', $codestring);
980 if ($codetype === $typewanted) {
981 // echo "<!-- returning '$code' -->\n"; // debugging
982 return $code;
984 $row = sqlQuery(
985 "SELECT related_code FROM codes WHERE " .
986 "code_type = ? AND code = ? AND active = 1 " .
987 "ORDER BY id LIMIT 1",
988 array($code_types[$codetype]['id'], $code)
990 $tmp = recursive_related_code($row['related_code'], $typewanted, $depth);
991 if ($tmp !== false) {
992 return $tmp;
995 return false;