increment v_database for prior commit
[openemr.git] / custom / code_types.inc.php
blob7b9d94cda8d9d316ede3570a4ee0769fd7ddaac4
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 * @copyright Copyright (c) 2021-2022 Robert Down <robertdown@live.com>
51 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
54 use OpenEMR\Events\Codes\ExternalCodesCreatedEvent;
55 use Symfony\Component\EventDispatcher\EventDispatcher;
57 require_once(__DIR__ . "/../library/csv_like_join.php");
59 $code_types = array();
60 global $code_types;
61 $ctres = sqlStatement("SELECT * FROM code_types WHERE ct_active=1 ORDER BY ct_seq, ct_key");
62 while ($ctrow = sqlFetchArray($ctres)) {
63 $code_types[$ctrow['ct_key']] = array(
64 'active' => $ctrow['ct_active' ],
65 'id' => $ctrow['ct_id' ],
66 'fee' => $ctrow['ct_fee' ],
67 'mod' => $ctrow['ct_mod' ],
68 'just' => $ctrow['ct_just'],
69 'rel' => $ctrow['ct_rel' ],
70 'nofs' => $ctrow['ct_nofs'],
71 'diag' => $ctrow['ct_diag'],
72 'mask' => $ctrow['ct_mask'],
73 'label' => ( (empty($ctrow['ct_label'])) ? $ctrow['ct_key'] : $ctrow['ct_label'] ),
74 'external' => $ctrow['ct_external'],
75 'claim' => $ctrow['ct_claim'],
76 'proc' => $ctrow['ct_proc'],
77 'term' => $ctrow['ct_term'],
78 'problem' => $ctrow['ct_problem'],
79 'drug' => $ctrow['ct_drug']
81 if (!array_key_exists($GLOBALS['default_search_code_type'], $code_types)) {
82 reset($code_types);
83 $GLOBALS['default_search_code_type'] = key($code_types);
87 /** This array contains metadata describing the arrangement of the external data
88 * tables for storing codes.
90 $code_external_tables = array();
91 global $code_external_tables;
92 define('EXT_COL_CODE', 'code');
93 define('EXT_COL_DESCRIPTION', 'description');
94 define('EXT_COL_DESCRIPTION_BRIEF', 'description_brief');
95 define('EXT_TABLE_NAME', 'table');
96 define('EXT_FILTER_CLAUSES', 'filter_clause');
97 define('EXT_VERSION_ORDER', 'filter_version_order');
98 define('EXT_JOINS', 'joins');
99 define('JOIN_TABLE', 'join');
100 define('JOIN_FIELDS', 'fields');
101 define('DISPLAY_DESCRIPTION', "display_description");
104 * This is a helper function for defining the metadata that describes the tables
106 * @param type $results A reference to the global array which stores all the metadata
107 * @param type $index The external table ID. This corresponds to the value in the code_types table in the ct_external column
108 * @param type $table_name The name of the table which stores the code informattion (e.g. icd9_dx_code
109 * @param type $col_code The name of the column which is the code
110 * @param type $col_description The name of the column which is the description
111 * @param type $col_description_brief The name of the column which is the brief description
112 * @param type $filter_clauses An array of clauses to be included in the search "WHERE" clause that limits results
113 * @param type $version_order How to choose between different revisions of codes
114 * @param type $joins An array which describes additional tables to join as part of a code search.
116 function define_external_table(&$results, $index, $table_name, $col_code, $col_description, $col_description_brief, $filter_clauses = array(), $version_order = "", $joins = array(), $display_desc = "")
118 $results[$index] = array(EXT_TABLE_NAME => $table_name,
119 EXT_COL_CODE => $col_code,
120 EXT_COL_DESCRIPTION => $col_description,
121 EXT_COL_DESCRIPTION_BRIEF => $col_description_brief,
122 EXT_FILTER_CLAUSES => $filter_clauses,
123 EXT_JOINS => $joins,
124 EXT_VERSION_ORDER => $version_order,
125 DISPLAY_DESCRIPTION => $display_desc
128 // In order to treat all the code types the same for lookup_code_descriptions, we include metadata for the original codes table
129 define_external_table($code_external_tables, 0, 'codes', 'code', 'code_text', 'code_text_short', array(), 'id');
131 // ICD9 External Definitions
132 define_external_table($code_external_tables, 4, 'icd9_dx_code', 'formatted_dx_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
133 define_external_table($code_external_tables, 5, 'icd9_sg_code', 'formatted_sg_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
134 //**** End ICD9 External Definitions
136 // SNOMED Definitions
137 // For generic SNOMED-CT, there is no need to join with the descriptions table to get a specific description Type
139 // For generic concepts, use the fully specified description (DescriptionType=3) so we can tell the difference between them.
140 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)'");
156 // SNOMED RF2 definitions
157 define_external_table($code_external_tables, 11, 'sct2_description', 'conceptId', 'term', 'term', array("active=1"), "");
158 if (isSnomedSpanish()) {
159 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(trastorno)'"), "");
160 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedimiento)'"), "");
161 } else {
162 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(disorder)'"), "");
163 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedure)'"), "");
166 //**** End SNOMED Definitions
168 // ICD 10 Definitions
169 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');
170 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');
171 //**** End ICD 10 Definitions
173 define_external_table($code_external_tables, 13, 'valueset', 'code', 'description', 'description', array(), '');
174 define_external_table($code_external_tables, 14, 'valueset_oid', 'code', 'description', 'description', array(), '');
177 * This array stores the external table options. See above for $code_types array
178 * 'external' attribute for explanation of the option listings.
179 * @var array
181 global $ct_external_options;
182 $ct_external_options = array(
183 '0' => xl('No'),
184 '4' => xl('ICD9 Diagnosis'),
185 '5' => xl('ICD9 Procedure/Service'),
186 '1' => xl('ICD10 Diagnosis'),
187 '6' => xl('ICD10 Procedure/Service'),
188 '2' => xl('SNOMED (RF1) Diagnosis'),
189 '7' => xl('SNOMED (RF1) Clinical Term'),
190 '9' => xl('SNOMED (RF1) Procedure'),
191 '10' => xl('SNOMED (RF2) Diagnosis'),
192 '11' => xl('SNOMED (RF2) Clinical Term'),
193 '12' => xl('SNOMED (RF2) Procedure'),
194 '13' => xl('CQM (Mixed Types) Value Set'),
195 '14' => xl('CQM OID Value Set')
199 * @var EventDispatcher
201 $eventDispatcher = $GLOBALS['kernel']->getEventDispatcher();
202 $externalCodesEvent = new ExternalCodesCreatedEvent($ct_external_options);
203 $eventDispatcher->dispatch($externalCodesEvent, ExternalCodesCreatedEvent::EVENT_HANDLE);
204 $ct_external_options = $externalCodesEvent->getExternalCodeData();
207 * Checks to see if using spanish snomed
209 function isSnomedSpanish()
211 // See if most recent SNOMED entry is International:Spanish
212 $sql = sqlQuery("SELECT `revision_version` FROM `standardized_tables_track` WHERE `name` = 'SNOMED' ORDER BY `id` DESC");
213 if ((!empty($sql)) && ($sql['revision_version'] == "International:Spanish")) {
214 return true;
216 return false;
220 * Checks is fee are applicable to any of the code types.
222 * @return boolean
224 function fees_are_used()
226 global $code_types;
227 foreach ($code_types as $value) {
228 if ($value['fee'] && $value['active']) {
229 return true;
233 return false;
237 * Checks if modifiers are applicable to any of the code types.
238 * (If a code type is not set to show in the fee sheet, then is ignored)
240 * @param boolean $fee_sheet Will ignore code types that are not shown in the fee sheet
241 * @return boolean
243 function modifiers_are_used($fee_sheet = false)
245 global $code_types;
246 foreach ($code_types as $value) {
247 if ($fee_sheet && !empty($value['nofs'])) {
248 continue;
251 if ($value['mod'] && $value['active']) {
252 return true;
256 return false;
260 * Checks if justifiers are applicable to any of the code types.
262 * @return boolean
264 function justifiers_are_used()
266 global $code_types;
267 foreach ($code_types as $value) {
268 if (!empty($value['just']) && $value['active']) {
269 return true;
273 return false;
277 * Checks is related codes are applicable to any of the code types.
279 * @return boolean
281 function related_codes_are_used()
283 global $code_types;
284 foreach ($code_types as $value) {
285 if ($value['rel'] && $value['active']) {
286 return true;
290 return false;
294 * Convert a code type id (ct_id) to the key string (ct_key)
296 * @param integer $id
297 * @return string
299 function convert_type_id_to_key($id)
301 global $code_types;
302 foreach ($code_types as $key => $value) {
303 if ($value['id'] == $id) {
304 return $key;
310 * Checks to see if code allows justification (ct_just)
312 * @param string $key
313 * @return boolean
315 function check_is_code_type_justify($key)
317 global $code_types;
319 if (!empty($code_types[$key]['just'])) {
320 return true;
321 } else {
322 return false;
327 * Checks if a key string (ct_key) is selected for an element/filter(s)
329 * @param string $key
330 * @param array $filter (array of elements that can include 'active','fee','rel','nofs','diag','claim','proc','term','problem')
331 * @return boolean
333 function check_code_set_filters($key, $filters = array())
335 global $code_types;
337 if (empty($filters)) {
338 return false;
341 foreach ($filters as $filter) {
342 if (array_key_exists($key, $code_types)) {
343 if ($code_types[$key][$filter] != 1) {
344 return false;
349 // Filter was passed
350 return true;
354 * Return listing of pertinent and active code types.
356 * Function will return listing (ct_key) of pertinent
357 * active code types, such as diagnosis codes or procedure
358 * codes in a chosen format. Supported returned formats include
359 * as 1) an array and as 2) a comma-separated lists that has been
360 * process by urlencode() in order to place into URL address safely.
362 * @param string $category category of code types('diagnosis', 'procedure', 'clinical_term', 'active' or 'medical_problem')
363 * @param string $return_format format or returned code types ('array' or 'csv')
364 * @return string/array
366 function collect_codetypes($category, $return_format = "array")
368 global $code_types;
370 $return = array();
372 foreach ($code_types as $ct_key => $ct_arr) {
373 if (!$ct_arr['active']) {
374 continue;
377 if ($category == "diagnosis") {
378 if ($ct_arr['diag']) {
379 $return[] = $ct_key;
381 } elseif ($category == "procedure") {
382 if ($ct_arr['proc']) {
383 $return[] = $ct_key;
385 } elseif ($category == "clinical_term") {
386 if ($ct_arr['term']) {
387 $return[] = $ct_key;
389 } elseif ($category == "active") {
390 if ($ct_arr['active']) {
391 $return[] = $ct_key;
393 } elseif ($category == "medical_problem") {
394 if ($ct_arr['problem']) {
395 $return[] = $ct_key;
397 } elseif ($category == "drug") {
398 if ($ct_arr['drug']) {
399 $return[] = $ct_key;
401 } else {
402 //return nothing since no supported category was chosen
406 if ($return_format == "csv") {
407 //return it as a csv string
408 return csv_like_join($return);
411 //$return_format == "array"
412 //return the array
413 return $return;
417 * Return the code information for a specific code.
419 * Function is able to search a variety of code sets. See the code type items in the comments at top
420 * of this page for a listing of the code sets supported.
422 * @param string $form_code_type code set key
423 * @param string $code code
424 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
425 * @return mixed recordset - will contain only one item (row).
427 function return_code_information($form_code_type, $code, $active = true)
429 return code_set_search($form_code_type, $code, false, $active, true);
433 * The main code set searching function.
435 * It will work for searching one or numerous code sets simultaneously.
436 * Note that when searching numerous code sets, you CAN NOT search the PROD
437 * codes; the PROD codes can only be searched by itself.
439 * @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
440 * @param string $search_term search term
441 * @param integer $limit Number of results to return (NULL means return all)
442 * @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)
443 * @param boolean $active if true, then will only return active entries
444 * @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)
445 * @param boolean $count if true, then will only return the number of entries
446 * @param integer $start Query start limit (for pagination) (Note this setting will override the above $limit parameter)
447 * @param integer $number Query number returned (for pagination) (Note this setting will override the above $limit parameter)
448 * @param array $filter_elements Array that contains elements to filter
449 * @return mixed recordset/integer - Will contain either a integer(if counting) or the results (recordset)
451 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())
454 // check for a category
455 if (!empty($category)) {
456 $form_code_type = collect_codetypes($category, "array");
459 // do the search
460 if (!empty($form_code_type)) {
461 if (is_array($form_code_type) && (count($form_code_type) > 1)) {
462 // run the multiple code set search
463 return multiple_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
466 if (is_array($form_code_type) && (count($form_code_type) == 1)) {
467 // prepare the variable (ie. convert the one array item to a string) for the non-multiple code set search
468 $form_code_type = $form_code_type[0];
471 // run the non-multiple code set search
472 return sequential_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
477 * Main "internal" code set searching function.
479 * Function is able to search a variety of code sets. See the 'external' items in the comments at top
480 * of this page for a listing of the code sets supported. Also note that Products (using PROD as code type)
481 * is also supported. (This function is not meant to be called directly)
483 * @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)
484 * @param string $search_term search term
485 * @param boolean $count if true, then will only return the number of entries
486 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
487 * @param boolean $return_only_one if true, then will only return one perfect matching item
488 * @param integer $start Query start limit
489 * @param integer $number Query number returned
490 * @param array $filter_elements Array that contains elements to filter
491 * @param integer $limit Number of results to return (NULL means return all); note this is ignored if set $start/number
492 * @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
493 * @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)
494 * @return mixed recordset/integer/array
496 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)
498 global $code_types, $code_external_tables;
500 // Figure out the appropriate limit clause
501 $limit_query = limit_query_string($limit, $start, $number, $return_only_one);
503 // build the filter_elements sql code
504 $query_filter_elements = "";
505 if (!empty($filter_elements)) {
506 foreach ($filter_elements as $key => $element) {
507 $query_filter_elements .= " AND codes." . add_escape_custom($key) . "=" . "'" . add_escape_custom($element) . "' ";
511 if ($form_code_type == 'PROD') { // Search for products/drugs
512 if ($count) {
513 $query = "SELECT count(dt.drug_id) as count ";
514 } else {
515 $query = "SELECT dt.drug_id, dt.selector, d.name ";
518 $query .= "FROM drug_templates AS dt, drugs AS d WHERE " .
519 "( d.name LIKE ? OR " .
520 "dt.selector LIKE ? ) " .
521 "AND d.drug_id = dt.drug_id " .
522 "ORDER BY d.name, dt.selector, dt.drug_id $limit_query";
523 $res = sqlStatement($query, array("%" . $search_term . "%", "%" . $search_term . "%"));
524 } else { // Start a codes search
525 // 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.
526 $table_id = isset($code_types[$form_code_type]['external']) ? intval(($code_types[$form_code_type]['external'])) : -9999 ;
527 if ($table_id >= 0) { // We found a definition for the given code search, so start building the query
528 // Place the common columns variable here since all check codes table
529 $common_columns = " codes.id, codes.code_type, codes.modifier, codes.units, codes.fee, " .
530 "codes.superbill, codes.related_code, codes.taxrates, codes.cyp_factor, " .
531 "codes.active, codes.reportable, codes.financial_reporting, codes.revenue_code, ";
532 $columns = $common_columns . "'" . add_escape_custom($form_code_type) . "' as code_type_name ";
534 $active_query = '';
535 if ($active) {
536 // Only filter for active codes. Only the active column in the joined table
537 // is affected by this parameter. Any filtering as a result of "active" status
538 // in the external table itself is always applied. I am implementing the behavior
539 // just as was done prior to the refactor
540 // - Kevin Yeh
541 // If there is no entry in codes sql table, then default to active
542 // (this is reason for including NULL below)
543 if ($table_id == 0) {
544 // Search from default codes table
545 $active_query = " AND codes.active = 1 ";
546 } else {
547 // Search from external tables
548 $active_query = " AND (codes.active = 1 || codes.active IS NULL) ";
552 // Get/set the basic metadata information
553 $table_info = $code_external_tables[$table_id];
554 $table = $table_info[EXT_TABLE_NAME];
555 $table_dot = $table . ".";
556 $code_col = $table_info[EXT_COL_CODE];
557 $code_text_col = $table_info[EXT_COL_DESCRIPTION];
558 $code_text_short_col = $table_info[EXT_COL_DESCRIPTION_BRIEF];
559 if ($table_id == 0) {
560 $table_info[EXT_FILTER_CLAUSES] = array("code_type=" . $code_types[$form_code_type]['id']); // Add a filter for the code type
563 $code_external = $code_types[$form_code_type]['external'];
565 // If the description is supposed to come from "joined" table instead of the "main",
566 // the metadata defines a DISPLAY_DESCRIPTION element, and we use that to build up the query
567 if ($table_info[DISPLAY_DESCRIPTION] != "") {
568 $display_description = $table_info[DISPLAY_DESCRIPTION];
569 $display_description_brief = $table_info[DISPLAY_DESCRIPTION];
570 } else {
571 $display_description = $table_dot . $code_text_col;
572 $display_description_brief = $table_dot . $code_text_short_col;
575 // Ensure the external table exists
576 $check_table = sqlQuery("SHOW TABLES LIKE '" . $table . "'");
577 if ((empty($check_table))) {
578 HelpfulDie("Missing table in code set search:" . $table);
581 $sql_bind_array = array();
582 if ($count) {
583 // only collecting a count
584 $query = "SELECT count(" . $table_dot . $code_col . ") as count ";
585 } else {
586 $substitute = '';
587 if ($table_dot === 'valueset.') {
588 $substitute = 'valueset.code_type as valueset_code_type, ';
590 $query = "SELECT '" . $code_external . "' as code_external, " .
591 $table_dot . $code_col . " as code, " .
592 $display_description . " as code_text, " .
593 $display_description_brief . " as code_text_short, " .
594 $substitute . $columns . " ";
597 if ($table_id == 0) {
598 // Search from default codes table
599 $query .= " FROM " . $table . " ";
600 } else {
601 // Search from external tables
602 $query .= " FROM " . $table .
603 " LEFT OUTER JOIN `codes` " .
604 " ON " . $table_dot . $code_col . " = codes.code AND codes.code_type = ? ";
605 $sql_bind_array[] = $code_types[$form_code_type]['id'];
608 foreach ($table_info[EXT_JOINS] as $join_info) {
609 $join_table = $join_info[JOIN_TABLE];
610 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
611 if ((empty($check_table))) {
612 HelpfulDie("Missing join table in code set search:" . $join_table);
615 $query .= " INNER JOIN " . $join_table;
616 $query .= " ON ";
617 $not_first = false;
618 foreach ($join_info[JOIN_FIELDS] as $field) {
619 if ($not_first) {
620 $query .= " AND ";
623 $query .= $field;
624 $not_first = true;
628 // Setup the where clause based on MODE
629 $query .= " WHERE ";
630 if ($return_only_one) {
631 $query .= $table_dot . $code_col . " = ? ";
632 $sql_bind_array[] = $search_term;
633 } elseif ($mode == "code") {
634 $query .= $table_dot . $code_col . " like ? ";
635 $sql_bind_array[] = $search_term . "%";
636 } elseif ($mode == "description") {
637 $description_keywords = preg_split("/ /", $search_term, -1, PREG_SPLIT_NO_EMPTY);
638 $query .= "(1=1 ";
639 foreach ($description_keywords as $keyword) {
640 $query .= " AND " . $table_dot . $code_text_col . " LIKE ? ";
641 $sql_bind_array[] = "%" . $keyword . "%";
644 $query .= ")";
645 } else { // $mode == "default"
646 $query .= "(" . $table_dot . $code_text_col . " LIKE ? OR " . $table_dot . $code_col . " LIKE ?) ";
647 array_push($sql_bind_array, "%" . $search_term . "%", "%" . $search_term . "%");
650 // Done setting up the where clause by mode
652 // Add the metadata related filter clauses
653 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
654 $query .= " AND ";
655 $dot_location = strpos($filter_clause, ".");
656 if ($dot_location !== false) {
657 // The filter clause already includes a table specifier, so don't add one
658 $query .= $filter_clause;
659 } else {
660 $query .= $table_dot . $filter_clause;
664 $query .= $active_query . $query_filter_elements;
666 $query .= " ORDER BY " . $table_dot . $code_col . "+0," . $table_dot . $code_col;
668 if ($return_query) {
669 // Just returning the actual query without the LIMIT information in it. This
670 // information can then be used to combine queries of different code types
671 // via the mysql UNION command. Returning an array to contain the query string
672 // and the binding parameters.
673 return array('query' => $query,'binds' => $sql_bind_array);
676 $query .= $limit_query;
678 $res = sqlStatement($query, $sql_bind_array);
679 } else {
680 HelpfulDie("Code type not active or not defined:" . $join_info[JOIN_TABLE]);
682 } // End specific code type search
684 if (isset($res)) {
685 if ($count) {
686 // just return the count
687 $ret = sqlFetchArray($res);
688 return $ret['count'];
690 // return the data
691 return $res;
696 * Lookup Code Descriptions for one or more billing codes.
698 * Function is able to lookup code descriptions from a variety of code sets. See the 'external'
699 * items in the comments at top of this page for a listing of the code sets supported.
701 * @param string $codes Is of the form "type:code;type:code; etc.".
702 * @param string $desc_detail Can choose either the normal description('code_text') or the brief description('code_text_short').
703 * @return string Is of the form "description;description; etc.".
705 function lookup_code_descriptions($codes, $desc_detail = "code_text")
707 global $code_types, $code_external_tables;
709 // ensure $desc_detail is set properly
710 if (($desc_detail != "code_text") && ($desc_detail != "code_text_short")) {
711 $desc_detail = "code_text";
714 $code_text = '';
715 if (!empty($codes)) {
716 $relcodes = explode(';', $codes);
717 foreach ($relcodes as $codestring) {
718 if ($codestring === '') {
719 continue;
722 // added $modifier for HCPCS and other internal codesets so can grab exact entry in codes table
723 $code_parts = explode(':', $codestring);
724 $codetype = $code_parts[0] ?? null;
725 $code = $code_parts[1] ?? null;
726 $modifier = $code_parts[2] ?? null;
727 // if we don't have the code types we can't do much here
728 if (!isset($code_types[$codetype])) {
729 // we can't do much so we will just continue here...
730 continue;
733 $table_id = $code_types[$codetype]['external'] ?? '';
734 if (!isset($code_external_tables[$table_id])) {
735 //using an external code that is not yet supported, so skip.
736 continue;
739 $table_info = $code_external_tables[$table_id];
740 $table_name = $table_info[EXT_TABLE_NAME];
741 $code_col = $table_info[EXT_COL_CODE];
742 $desc_col = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION] : $table_info[DISPLAY_DESCRIPTION];
743 $desc_col_short = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION_BRIEF] : $table_info[DISPLAY_DESCRIPTION];
744 $sqlArray = array();
745 $sql = "SELECT " . $desc_col . " as code_text," . $desc_col_short . " as code_text_short FROM " . $table_name;
747 // include the "JOINS" so that we get the preferred term instead of the FullySpecifiedName when appropriate.
748 foreach ($table_info[EXT_JOINS] as $join_info) {
749 $join_table = $join_info[JOIN_TABLE];
750 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
751 if ((empty($check_table))) {
752 HelpfulDie("Missing join table in code set search:" . $join_table);
755 $sql .= " INNER JOIN " . $join_table;
756 $sql .= " ON ";
757 $not_first = false;
758 foreach ($join_info[JOIN_FIELDS] as $field) {
759 if ($not_first) {
760 $sql .= " AND ";
763 $sql .= $field;
764 $not_first = true;
768 $sql .= " WHERE ";
771 // Start building up the WHERE clause
773 // When using the external codes table, we have to filter by the code_type. (All the other tables only contain one type)
774 if ($table_id == 0) {
775 $sql .= " code_type = '" . add_escape_custom($code_types[$codetype]['id']) . "' AND ";
778 // Specify the code in the query.
779 $sql .= $table_name . "." . $code_col . "=? ";
780 $sqlArray[] = $code;
782 // Add the modifier if necessary for CPT and HCPCS which differentiates code
783 if ($modifier) {
784 $sql .= " AND modifier = ? ";
785 $sqlArray[] = $modifier;
788 // We need to include the filter clauses
789 // For SNOMED and SNOMED-CT this ensures that we get the Preferred Term or the Fully Specified Term as appropriate
790 // It also prevents returning "inactive" results
791 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
792 $sql .= " AND " . $filter_clause;
795 // END building the WHERE CLAUSE
798 if ($table_info[EXT_VERSION_ORDER]) {
799 $sql .= " ORDER BY " . $table_info[EXT_VERSION_ORDER];
802 $sql .= " LIMIT 1";
803 $crow = sqlQuery($sql, $sqlArray);
804 if (!empty($crow[$desc_detail])) {
805 if ($code_text) {
806 $code_text .= '; ';
809 $code_text .= $crow[$desc_detail];
814 return $code_text;
818 * Sequential code set "internal" searching function
820 * Function is basically a wrapper of the code_set_search() function to support
821 * a optimized searching models. The default mode will:
822 * Searches codes first; then if no hits, it will then search the descriptions
823 * (which are separated by each word in the code_set_search() function).
824 * (This function is not meant to be called directly)
826 * @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)
827 * @param string $search_term search term
828 * @param integer $limit Number of results to return (NULL means return all)
829 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
830 * @param boolean $count if true, then will only return the number of entries
831 * @param boolean $active if true, then will only return active entries
832 * @param integer $start Query start limit (for pagination)
833 * @param integer $number Query number returned (for pagination)
834 * @param array $filter_elements Array that contains elements to filter
835 * @param string $is_hit_mode This is a mode that simply returns the name of the mode if results were found
836 * @return mixed recordset/integer/string
838 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)
840 // Set the default behavior that is described in above function comments
841 if (empty($modes)) {
842 $modes = array('code','description');
845 // Return the Search Results (loop through each mode in order)
846 foreach ($modes as $mode) {
847 $res = code_set_search($form_code_type, $search_term, $count, $active, false, $start, $number, $filter_elements, $limit, $mode);
848 if (($count && $res > 0) || (!$count && sqlNumRows($res) > 0)) {
849 if ($is_hit_mode) {
850 // just return the mode
851 return $mode;
852 } else {
853 // returns the count number if count is true or returns the data if count is false
854 return $res;
861 * Code set searching "internal" function for when searching multiple code sets.
863 * It will also work for one code set search, although not meant for this.
864 * (This function is not meant to be called directly)
866 * @param array $form_code_types code set keys (will default to checking all active code types if blank)
867 * @param string $search_term search term
868 * @param integer $limit Number of results to return (NULL means return all)
869 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
870 * @param boolean $count if true, then will only return the number of entries
871 * @param boolean $active if true, then will only return active entries
872 * @param integer $start Query start limit (for pagination)
873 * @param integer $number Query number returned (for pagination)
874 * @param array $filter_elements Array that contains elements to filter
875 * @return mixed recordset/integer
877 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())
880 if (empty($form_code_types)) {
881 // Collect the active code types
882 $form_code_types = collect_codetypes("active", "array");
885 if ($count) {
886 //start the counter
887 $counter = 0;
888 } else {
889 // Figure out the appropriate limit clause
890 $limit_query = limit_query_string($limit, $start, $number);
892 // Prepare the sql bind array
893 $sql_bind_array = array();
895 // Start the query string
896 $query = "SELECT * FROM ((";
899 // Loop through each code type
900 $flag_first = true;
901 $flag_hit = false; //ensure there is a hit to avoid trying an empty query
902 foreach ($form_code_types as $form_code_type) {
903 // see if there is a hit
904 $mode_hit = null;
905 // only use the count method here, since it's much more efficient than doing the actual query
906 $mode_hit = sequential_code_set_search($form_code_type, $search_term, null, $modes, true, $active, null, null, $filter_elements, true);
907 if ($mode_hit) {
908 if ($count) {
909 // count the hits
910 $count_hits = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit);
911 // increment the counter
912 $counter += $count_hits;
913 } else {
914 $flag_hit = true;
915 // build the query
916 $return_query = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit, true);
917 if (!empty($sql_bind_array)) {
918 $sql_bind_array = array_merge($sql_bind_array, $return_query['binds']);
919 } else {
920 $sql_bind_array = $return_query['binds'];
923 if (!$flag_first) {
924 $query .= ") UNION ALL (";
927 $query .= $return_query['query'];
930 $flag_first = false;
934 if ($count) {
935 //return the count
936 return $counter;
937 } else {
938 // Finish the query string
939 $query .= ")) as atari $limit_query";
941 // Process and return the query (if there was a hit)
942 if ($flag_hit) {
943 return sqlStatement($query, $sql_bind_array);
949 * Returns the limit to be used in the sql query for code set searches.
951 * @param integer $limit Number of results to return (NULL means return all)
952 * @param integer $start Query start limit (for pagination)
953 * @param integer $number Query number returned (for pagination)
954 * @param boolean $return_only_one if true, then will only return one perfect matching item
955 * @return mixed recordset/integer
957 function limit_query_string($limit = null, $start = null, $number = null, $return_only_one = false)
959 if (!is_null($start) && !is_null($number)) {
960 // For pagination of results
961 $limit_query = " LIMIT " . escape_limit($start) . ", " . escape_limit($number) . " ";
962 } elseif (!is_null($limit)) {
963 $limit_query = " LIMIT " . escape_limit($limit) . " ";
964 } else {
965 // No pagination and no limit
966 $limit_query = '';
969 if ($return_only_one) {
970 // Only return one result (this is where only matching for exact code match)
971 // Note this overrides the above limit settings
972 $limit_query = " LIMIT 1 ";
975 return $limit_query;
978 // Recursive function to look up the IPPF2 (or other type) code, if any,
979 // for a given related code field.
981 function recursive_related_code($related_code, $typewanted = 'IPPF2', $depth = 0)
983 global $code_types;
984 // echo "<!-- related_code = '$related_code' depth = '$depth' -->\n"; // debugging
985 if (++$depth > 4 || empty($related_code)) {
986 return false; // protects against relation loops
988 $relcodes = explode(';', $related_code);
989 foreach ($relcodes as $codestring) {
990 if ($codestring === '') {
991 continue;
993 list($codetype, $code) = explode(':', $codestring);
994 if ($codetype === $typewanted) {
995 // echo "<!-- returning '$code' -->\n"; // debugging
996 return $code;
998 $row = sqlQuery(
999 "SELECT related_code FROM codes WHERE " .
1000 "code_type = ? AND code = ? AND active = 1 " .
1001 "ORDER BY id LIMIT 1",
1002 array($code_types[$codetype]['id'], $code)
1004 $tmp = recursive_related_code($row['related_code'], $typewanted, $depth);
1005 if ($tmp !== false) {
1006 return $tmp;
1009 return false;