Followup commit to complete the renaming and replacement of pos_checkout.php.
[openemr.git] / custom / code_types.inc.php
blob9f111840a70c5454cb4a7bfb824f02ad13297db2
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 $default_search_type = $GLOBALS['default_search_code_type'];
78 } else {
79 reset($code_types);
80 $default_search_type = key($code_types);
84 /** This array contains metadata describing the arrangement of the external data
85 * tables for storing codes.
87 $code_external_tables = array();
88 global $code_external_tables;
89 define('EXT_COL_CODE', 'code');
90 define('EXT_COL_DESCRIPTION', 'description');
91 define('EXT_COL_DESCRIPTION_BRIEF', 'description_brief');
92 define('EXT_TABLE_NAME', 'table');
93 define('EXT_FILTER_CLAUSES', 'filter_clause');
94 define('EXT_VERSION_ORDER', 'filter_version_order');
95 define('EXT_JOINS', 'joins');
96 define('JOIN_TABLE', 'join');
97 define('JOIN_FIELDS', 'fields');
98 define('DISPLAY_DESCRIPTION', "display_description");
101 * This is a helper function for defining the metadata that describes the tables
103 * @param type $results A reference to the global array which stores all the metadata
104 * @param type $index The external table ID. This corresponds to the value in the code_types table in the ct_external column
105 * @param type $table_name The name of the table which stores the code informattion (e.g. icd9_dx_code
106 * @param type $col_code The name of the column which is the code
107 * @param type $col_description The name of the column which is the description
108 * @param type $col_description_brief The name of the column which is the brief description
109 * @param type $filter_clauses An array of clauses to be included in the search "WHERE" clause that limits results
110 * @param type $version_order How to choose between different revisions of codes
111 * @param type $joins An array which describes additional tables to join as part of a code search.
113 function define_external_table(&$results, $index, $table_name, $col_code, $col_description, $col_description_brief, $filter_clauses = array(), $version_order = "", $joins = array(), $display_desc = "")
115 $results[$index] = array(EXT_TABLE_NAME => $table_name,
116 EXT_COL_CODE => $col_code,
117 EXT_COL_DESCRIPTION => $col_description,
118 EXT_COL_DESCRIPTION_BRIEF => $col_description_brief,
119 EXT_FILTER_CLAUSES => $filter_clauses,
120 EXT_JOINS => $joins,
121 EXT_VERSION_ORDER => $version_order,
122 DISPLAY_DESCRIPTION => $display_desc
125 // In order to treat all the code types the same for lookup_code_descriptions, we include metadata for the original codes table
126 define_external_table($code_external_tables, 0, 'codes', 'code', 'code_text', 'code_text_short', array(), 'id');
128 // ICD9 External Definitions
129 define_external_table($code_external_tables, 4, 'icd9_dx_code', 'formatted_dx_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
130 define_external_table($code_external_tables, 5, 'icd9_sg_code', 'formatted_sg_code', 'long_desc', 'short_desc', array("active='1'"), 'revision DESC');
131 //**** End ICD9 External Definitions
133 // SNOMED Definitions
134 // For generic SNOMED-CT, there is no need to join with the descriptions table to get a specific description Type
136 // For generic concepts, use the fully specified description (DescriptionType=3) so we can tell the difference between them.
137 define_external_table($code_external_tables, 7, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=3"), "");
139 // To determine codes, we need to evaluate data in both the sct_descriptions table, and the sct_concepts table.
140 // the base join with sct_concepts is the same for all types of SNOMED definitions, so we define the common part here
141 $SNOMED_joins = array(JOIN_TABLE => "sct_concepts",JOIN_FIELDS => array("sct_descriptions.ConceptId=sct_concepts.ConceptId"));
143 // For disorders, use the preferred term (DescriptionType=1)
144 define_external_table($code_external_tables, 2, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=1"), "", array($SNOMED_joins));
145 // Add the filter to choose only disorders. This filter happens as part of the join with the sct_concepts table
146 array_push($code_external_tables[2][EXT_JOINS][0][JOIN_FIELDS], "FullySpecifiedName like '%(disorder)'");
148 // SNOMED-PR definition
149 define_external_table($code_external_tables, 9, 'sct_descriptions', 'ConceptId', 'Term', 'Term', array("DescriptionStatus=0","DescriptionType=1"), "", array($SNOMED_joins));
150 // Add the filter to choose only procedures. This filter happens as part of the join with the sct_concepts table
151 array_push($code_external_tables[9][EXT_JOINS][0][JOIN_FIELDS], "FullySpecifiedName like '%(procedure)'");
153 // SNOMED RF2 definitions
154 define_external_table($code_external_tables, 11, 'sct2_description', 'conceptId', 'term', 'term', array("active=1"), "");
155 if (isSnomedSpanish()) {
156 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(trastorno)'"), "");
157 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedimiento)'"), "");
158 } else {
159 define_external_table($code_external_tables, 10, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(disorder)'"), "");
160 define_external_table($code_external_tables, 12, 'sct2_description', 'conceptId', 'term', 'term', array("active=1", "term LIKE '%(procedure)'"), "");
163 //**** End SNOMED Definitions
165 // ICD 10 Definitions
166 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');
167 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');
168 //**** End ICD 10 Definitions
171 * This array stores the external table options. See above for $code_types array
172 * 'external' attribute for explanation of the option listings.
173 * @var array
175 global $ct_external_options;
176 $ct_external_options = array(
177 '0' => xl('No'),
178 '4' => xl('ICD9 Diagnosis'),
179 '5' => xl('ICD9 Procedure/Service'),
180 '1' => xl('ICD10 Diagnosis'),
181 '6' => xl('ICD10 Procedure/Service'),
182 '2' => xl('SNOMED (RF1) Diagnosis'),
183 '7' => xl('SNOMED (RF1) Clinical Term'),
184 '9' => xl('SNOMED (RF1) Procedure'),
185 '10' => xl('SNOMED (RF2) Diagnosis'),
186 '11' => xl('SNOMED (RF2) Clinical Term'),
187 '12' => xl('SNOMED (RF2) Procedure')
191 * Checks to see if using spanish snomed
193 function isSnomedSpanish()
195 // See if most recent SNOMED entry is International:Spanish
196 $sql = sqlQuery("SELECT `revision_version` FROM `standardized_tables_track` WHERE `name` = 'SNOMED' ORDER BY `id` DESC");
197 if ((!empty($sql)) && ($sql['revision_version'] == "International:Spanish")) {
198 return true;
200 return false;
204 * Checks is fee are applicable to any of the code types.
206 * @return boolean
208 function fees_are_used()
210 global $code_types;
211 foreach ($code_types as $value) {
212 if ($value['fee'] && $value['active']) {
213 return true;
217 return false;
221 * Checks is modifiers are applicable to any of the code types.
222 * (If a code type is not set to show in the fee sheet, then is ignored)
224 * @param boolean $fee_sheet Will ignore code types that are not shown in the fee sheet
225 * @return boolean
227 function modifiers_are_used($fee_sheet = false)
229 global $code_types;
230 foreach ($code_types as $value) {
231 if ($fee_sheet && !empty($value['nofs'])) {
232 continue;
235 if ($value['mod'] && $value['active']) {
236 return true;
240 return false;
244 * Checks if justifiers are applicable to any of the code types.
246 * @return boolean
248 function justifiers_are_used()
250 global $code_types;
251 foreach ($code_types as $value) {
252 if (!empty($value['just']) && $value['active']) {
253 return true;
257 return false;
261 * Checks is related codes are applicable to any of the code types.
263 * @return boolean
265 function related_codes_are_used()
267 global $code_types;
268 foreach ($code_types as $value) {
269 if ($value['rel'] && $value['active']) {
270 return true;
274 return false;
278 * Convert a code type id (ct_id) to the key string (ct_key)
280 * @param integer $id
281 * @return string
283 function convert_type_id_to_key($id)
285 global $code_types;
286 foreach ($code_types as $key => $value) {
287 if ($value['id'] == $id) {
288 return $key;
294 * Checks to see if code allows justification (ct_just)
296 * @param string $key
297 * @return boolean
299 function check_is_code_type_justify($key)
301 global $code_types;
303 if (!empty($code_types[$key]['just'])) {
304 return true;
305 } else {
306 return false;
311 * Checks if a key string (ct_key) is selected for an element/filter(s)
313 * @param string $key
314 * @param array $filter (array of elements that can include 'active','fee','rel','nofs','diag','claim','proc','term','problem')
315 * @return boolean
317 function check_code_set_filters($key, $filters = array())
319 global $code_types;
321 if (empty($filters)) {
322 return false;
325 foreach ($filters as $filter) {
326 if ($code_types[$key][$filter] != 1) {
327 return false;
331 // Filter was passed
332 return true;
336 * Return listing of pertinent and active code types.
338 * Function will return listing (ct_key) of pertinent
339 * active code types, such as diagnosis codes or procedure
340 * codes in a chosen format. Supported returned formats include
341 * as 1) an array and as 2) a comma-separated lists that has been
342 * process by urlencode() in order to place into URL address safely.
344 * @param string $category category of code types('diagnosis', 'procedure', 'clinical_term', 'active' or 'medical_problem')
345 * @param string $return_format format or returned code types ('array' or 'csv')
346 * @return string/array
348 function collect_codetypes($category, $return_format = "array")
350 global $code_types;
352 $return = array();
354 foreach ($code_types as $ct_key => $ct_arr) {
355 if (!$ct_arr['active']) {
356 continue;
359 if ($category == "diagnosis") {
360 if ($ct_arr['diag']) {
361 array_push($return, $ct_key);
363 } elseif ($category == "procedure") {
364 if ($ct_arr['proc']) {
365 array_push($return, $ct_key);
367 } elseif ($category == "clinical_term") {
368 if ($ct_arr['term']) {
369 array_push($return, $ct_key);
371 } elseif ($category == "active") {
372 if ($ct_arr['active']) {
373 array_push($return, $ct_key);
375 } elseif ($category == "medical_problem") {
376 if ($ct_arr['problem']) {
377 array_push($return, $ct_key);
379 } elseif ($category == "drug") {
380 if ($ct_arr['drug']) {
381 array_push($return, $ct_key);
383 } else {
384 //return nothing since no supported category was chosen
388 if ($return_format == "csv") {
389 //return it as a csv string
390 return csv_like_join($return);
391 } else { //$return_format == "array"
392 //return the array
393 return $return;
398 * Return the code information for a specific code.
400 * Function is able to search a variety of code sets. See the code type items in the comments at top
401 * of this page for a listing of the code sets supported.
403 * @param string $form_code_type code set key
404 * @param string $code code
405 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
406 * @return recordset will contain only one item (row).
408 function return_code_information($form_code_type, $code, $active = true)
410 return code_set_search($form_code_type, $code, false, $active, true);
414 * The main code set searching function.
416 * It will work for searching one or numerous code sets simultaneously.
417 * Note that when searching numerous code sets, you CAN NOT search the PROD
418 * codes; the PROD codes can only be searched by itself.
420 * @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
421 * @param string $search_term search term
422 * @param integer $limit Number of results to return (NULL means return all)
423 * @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)
424 * @param boolean $active if true, then will only return active entries
425 * @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)
426 * @param boolean $count if true, then will only return the number of entries
427 * @param integer $start Query start limit (for pagination) (Note this setting will override the above $limit parameter)
428 * @param integer $number Query number returned (for pagination) (Note this setting will override the above $limit parameter)
429 * @param array $filter_elements Array that contains elements to filter
430 * @return recordset/integer Will contain either a integer(if counting) or the results (recordset)
432 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())
435 // check for a category
436 if (!empty($category)) {
437 $form_code_type = collect_codetypes($category, "array");
440 // do the search
441 if (!empty($form_code_type)) {
442 if (is_array($form_code_type) && (count($form_code_type) > 1)) {
443 // run the multiple code set search
444 return multiple_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
447 if (is_array($form_code_type) && (count($form_code_type) == 1)) {
448 // prepare the variable (ie. convert the one array item to a string) for the non-multiple code set search
449 $form_code_type = $form_code_type[0];
452 // run the non-multiple code set search
453 return sequential_code_set_search($form_code_type, $search_term, $limit, $modes, $count, $active, $start, $number, $filter_elements);
458 * Main "internal" code set searching function.
460 * Function is able to search a variety of code sets. See the 'external' items in the comments at top
461 * of this page for a listing of the code sets supported. Also note that Products (using PROD as code type)
462 * is also supported. (This function is not meant to be called directly)
464 * @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)
465 * @param string $search_term search term
466 * @param boolean $count if true, then will only return the number of entries
467 * @param boolean $active if true, then will only return active entries (not pertinent for PROD code sets)
468 * @param boolean $return_only_one if true, then will only return one perfect matching item
469 * @param integer $start Query start limit
470 * @param integer $number Query number returned
471 * @param array $filter_elements Array that contains elements to filter
472 * @param integer $limit Number of results to return (NULL means return all); note this is ignored if set $start/number
473 * @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
474 * @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)
475 * @return recordset/integer/array
477 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)
479 global $code_types, $code_external_tables;
481 // Figure out the appropriate limit clause
482 $limit_query = limit_query_string($limit, $start, $number, $return_only_one);
484 // build the filter_elements sql code
485 $query_filter_elements = "";
486 if (!empty($filter_elements)) {
487 foreach ($filter_elements as $key => $element) {
488 $query_filter_elements .= " AND codes." . add_escape_custom($key) . "=" . "'" . add_escape_custom($element) . "' ";
492 if ($form_code_type == 'PROD') { // Search for products/drugs
493 if ($count) {
494 $query = "SELECT count(dt.drug_id) as count ";
495 } else {
496 $query = "SELECT dt.drug_id, dt.selector, d.name ";
499 $query .= "FROM drug_templates AS dt, drugs AS d WHERE " .
500 "( d.name LIKE ? OR " .
501 "dt.selector LIKE ? ) " .
502 "AND d.drug_id = dt.drug_id " .
503 "ORDER BY d.name, dt.selector, dt.drug_id $limit_query";
504 $res = sqlStatement($query, array("%" . $search_term . "%", "%" . $search_term . "%"));
505 } else { // Start a codes search
506 // 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.
507 $table_id = isset($code_types[$form_code_type]['external']) ? intval(($code_types[$form_code_type]['external'])) : -9999 ;
508 if ($table_id >= 0) { // We found a definition for the given code search, so start building the query
509 // Place the common columns variable here since all check codes table
510 $common_columns = " codes.id, codes.code_type, codes.modifier, codes.units, codes.fee, " .
511 "codes.superbill, codes.related_code, codes.taxrates, codes.cyp_factor, " .
512 "codes.active, codes.reportable, codes.financial_reporting, codes.revenue_code, ";
513 $columns = $common_columns . "'" . add_escape_custom($form_code_type) . "' as code_type_name ";
515 $active_query = '';
516 if ($active) {
517 // Only filter for active codes. Only the active column in the joined table
518 // is affected by this parameter. Any filtering as a result of "active" status
519 // in the external table itself is always applied. I am implementing the behavior
520 // just as was done prior to the refactor
521 // - Kevin Yeh
522 // If there is no entry in codes sql table, then default to active
523 // (this is reason for including NULL below)
524 if ($table_id == 0) {
525 // Search from default codes table
526 $active_query = " AND codes.active = 1 ";
527 } else {
528 // Search from external tables
529 $active_query = " AND (codes.active = 1 || codes.active IS NULL) ";
533 // Get/set the basic metadata information
534 $table_info = $code_external_tables[$table_id];
535 $table = $table_info[EXT_TABLE_NAME];
536 $table_dot = $table . ".";
537 $code_col = $table_info[EXT_COL_CODE];
538 $code_text_col = $table_info[EXT_COL_DESCRIPTION];
539 $code_text_short_col = $table_info[EXT_COL_DESCRIPTION_BRIEF];
540 if ($table_id == 0) {
541 $table_info[EXT_FILTER_CLAUSES] = array("code_type=" . $code_types[$form_code_type]['id']); // Add a filter for the code type
544 $code_external = $code_types[$form_code_type]['external'];
546 // If the description is supposed to come from "joined" table instead of the "main",
547 // the metadata defines a DISPLAY_DESCRIPTION element, and we use that to build up the query
548 if ($table_info[DISPLAY_DESCRIPTION] != "") {
549 $display_description = $table_info[DISPLAY_DESCRIPTION];
550 $display_description_brief = $table_info[DISPLAY_DESCRIPTION];
551 } else {
552 $display_description = $table_dot . $code_text_col;
553 $display_description_brief = $table_dot . $code_text_short_col;
556 // Ensure the external table exists
557 $check_table = sqlQuery("SHOW TABLES LIKE '" . $table . "'");
558 if ((empty($check_table))) {
559 HelpfulDie("Missing table in code set search:" . $table);
562 $sql_bind_array = array();
563 if ($count) {
564 // only collecting a count
565 $query = "SELECT count(" . $table_dot . $code_col . ") as count ";
566 } else {
567 $query = "SELECT '" . $code_external . "' as code_external, " .
568 $table_dot . $code_col . " as code, " .
569 $display_description . " as code_text, " .
570 $display_description_brief . " as code_text_short, " .
571 $columns . " ";
574 if ($table_id == 0) {
575 // Search from default codes table
576 $query .= " FROM " . $table . " ";
577 } else {
578 // Search from external tables
579 $query .= " FROM " . $table .
580 " LEFT OUTER JOIN `codes` " .
581 " ON " . $table_dot . $code_col . " = codes.code AND codes.code_type = ? ";
582 array_push($sql_bind_array, $code_types[$form_code_type]['id']);
585 foreach ($table_info[EXT_JOINS] as $join_info) {
586 $join_table = $join_info[JOIN_TABLE];
587 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
588 if ((empty($check_table))) {
589 HelpfulDie("Missing join table in code set search:" . $join_table);
592 $query .= " INNER JOIN " . $join_table;
593 $query .= " ON ";
594 $not_first = false;
595 foreach ($join_info[JOIN_FIELDS] as $field) {
596 if ($not_first) {
597 $query .= " AND ";
600 $query .= $field;
601 $not_first = true;
605 // Setup the where clause based on MODE
606 $query .= " WHERE ";
607 if ($return_only_one) {
608 $query .= $table_dot . $code_col . " = ? ";
609 array_push($sql_bind_array, $search_term);
610 } elseif ($mode == "code") {
611 $query .= $table_dot . $code_col . " like ? ";
612 array_push($sql_bind_array, $search_term . "%");
613 } elseif ($mode == "description") {
614 $description_keywords = preg_split("/ /", $search_term, -1, PREG_SPLIT_NO_EMPTY);
615 $query .= "(1=1 ";
616 foreach ($description_keywords as $keyword) {
617 $query .= " AND " . $table_dot . $code_text_col . " LIKE ? ";
618 array_push($sql_bind_array, "%" . $keyword . "%");
621 $query .= ")";
622 } else { // $mode == "default"
623 $query .= "(" . $table_dot . $code_text_col . " LIKE ? OR " . $table_dot . $code_col . " LIKE ?) ";
624 array_push($sql_bind_array, "%" . $search_term . "%", "%" . $search_term . "%");
627 // Done setting up the where clause by mode
629 // Add the metadata related filter clauses
630 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
631 $query .= " AND ";
632 $dot_location = strpos($filter_clause, ".");
633 if ($dot_location !== false) {
634 // The filter clause already includes a table specifier, so don't add one
635 $query .= $filter_clause;
636 } else {
637 $query .= $table_dot . $filter_clause;
641 $query .= $active_query . $query_filter_elements;
643 $query .= " ORDER BY " . $table_dot . $code_col . "+0," . $table_dot . $code_col;
645 if ($return_query) {
646 // Just returning the actual query without the LIMIT information in it. This
647 // information can then be used to combine queries of different code types
648 // via the mysql UNION command. Returning an array to contain the query string
649 // and the binding parameters.
650 return array('query' => $query,'binds' => $sql_bind_array);
653 $query .= $limit_query;
655 $res = sqlStatement($query, $sql_bind_array);
656 } else {
657 HelpfulDie("Code type not active or not defined:" . $join_info[JOIN_TABLE]);
659 } // End specific code type search
661 if (isset($res)) {
662 if ($count) {
663 // just return the count
664 $ret = sqlFetchArray($res);
665 return $ret['count'];
666 } else {
667 // return the data
668 return $res;
674 * Lookup Code Descriptions for one or more billing codes.
676 * Function is able to lookup code descriptions from a variety of code sets. See the 'external'
677 * items in the comments at top of this page for a listing of the code sets supported.
679 * @param string $codes Is of the form "type:code;type:code; etc.".
680 * @param string $desc_detail Can choose either the normal description('code_text') or the brief description('code_text_short').
681 * @return string Is of the form "description;description; etc.".
683 function lookup_code_descriptions($codes, $desc_detail = "code_text")
685 global $code_types, $code_external_tables;
687 // ensure $desc_detail is set properly
688 if (($desc_detail != "code_text") && ($desc_detail != "code_text_short")) {
689 $desc_detail = "code_text";
692 $code_text = '';
693 if (!empty($codes)) {
694 $relcodes = explode(';', $codes);
695 foreach ($relcodes as $codestring) {
696 if ($codestring === '') {
697 continue;
700 list($codetype, $code) = explode(':', $codestring);
701 $table_id = $code_types[$codetype]['external'] ?? '';
702 if (isset($code_external_tables[$table_id])) {
703 $table_info = $code_external_tables[$table_id];
704 $table_name = $table_info[EXT_TABLE_NAME];
705 $code_col = $table_info[EXT_COL_CODE];
706 $desc_col = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION] : $table_info[DISPLAY_DESCRIPTION];
707 $desc_col_short = $table_info[DISPLAY_DESCRIPTION] == "" ? $table_info[EXT_COL_DESCRIPTION_BRIEF] : $table_info[DISPLAY_DESCRIPTION];
708 $sqlArray = array();
709 $sql = "SELECT " . $desc_col . " as code_text," . $desc_col_short . " as code_text_short FROM " . $table_name;
711 // include the "JOINS" so that we get the preferred term instead of the FullySpecifiedName when appropriate.
712 foreach ($table_info[EXT_JOINS] as $join_info) {
713 $join_table = $join_info[JOIN_TABLE];
714 $check_table = sqlQuery("SHOW TABLES LIKE '" . $join_table . "'");
715 if ((empty($check_table))) {
716 HelpfulDie("Missing join table in code set search:" . $join_table);
719 $sql .= " INNER JOIN " . $join_table;
720 $sql .= " ON ";
721 $not_first = false;
722 foreach ($join_info[JOIN_FIELDS] as $field) {
723 if ($not_first) {
724 $sql .= " AND ";
727 $sql .= $field;
728 $not_first = true;
732 $sql .= " WHERE ";
735 // Start building up the WHERE clause
737 // When using the external codes table, we have to filter by the code_type. (All the other tables only contain one type)
738 if ($table_id == 0) {
739 $sql .= " code_type = '" . add_escape_custom($code_types[$codetype]['id']) . "' AND ";
742 // Specify the code in the query.
743 $sql .= $table_name . "." . $code_col . "=? ";
744 array_push($sqlArray, $code);
746 // We need to include the filter clauses
747 // For SNOMED and SNOMED-CT this ensures that we get the Preferred Term or the Fully Specified Term as appropriate
748 // It also prevents returning "inactive" results
749 foreach ($table_info[EXT_FILTER_CLAUSES] as $filter_clause) {
750 $sql .= " AND " . $filter_clause;
753 // END building the WHERE CLAUSE
756 if ($table_info[EXT_VERSION_ORDER]) {
757 $sql .= " ORDER BY " . $table_info[EXT_VERSION_ORDER];
760 $sql .= " LIMIT 1";
761 $crow = sqlQuery($sql, $sqlArray);
762 if (!empty($crow[$desc_detail])) {
763 if ($code_text) {
764 $code_text .= '; ';
767 $code_text .= $crow[$desc_detail];
769 } else {
770 //using an external code that is not yet supported, so skip.
775 return $code_text;
779 * Sequential code set "internal" searching function
781 * Function is basically a wrapper of the code_set_search() function to support
782 * a optimized searching models. The default mode will:
783 * Searches codes first; then if no hits, it will then search the descriptions
784 * (which are separated by each word in the code_set_search() function).
785 * (This function is not meant to be called directly)
787 * @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)
788 * @param string $search_term search term
789 * @param integer $limit Number of results to return (NULL means return all)
790 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
791 * @param boolean $count if true, then will only return the number of entries
792 * @param boolean $active if true, then will only return active entries
793 * @param integer $start Query start limit (for pagination)
794 * @param integer $number Query number returned (for pagination)
795 * @param array $filter_elements Array that contains elements to filter
796 * @param string $is_hit_mode This is a mode that simply returns the name of the mode if results were found
797 * @return recordset/integer/string
799 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)
801 // Set the default behavior that is described in above function comments
802 if (empty($modes)) {
803 $modes = array('code','description');
806 // Return the Search Results (loop through each mode in order)
807 foreach ($modes as $mode) {
808 $res = code_set_search($form_code_type, $search_term, $count, $active, false, $start, $number, $filter_elements, $limit, $mode);
809 if (($count && $res > 0) || (!$count && sqlNumRows($res) > 0)) {
810 if ($is_hit_mode) {
811 // just return the mode
812 return $mode;
813 } else {
814 // returns the count number if count is true or returns the data if count is false
815 return $res;
822 * Code set searching "internal" function for when searching multiple code sets.
824 * It will also work for one code set search, although not meant for this.
825 * (This function is not meant to be called directly)
827 * @param array $form_code_types code set keys (will default to checking all active code types if blank)
828 * @param string $search_term search term
829 * @param integer $limit Number of results to return (NULL means return all)
830 * @param array $modes Holds the search modes to process along with the order of processing (default behavior is described in above function comment)
831 * @param boolean $count if true, then will only return the number of entries
832 * @param boolean $active if true, then will only return active entries
833 * @param integer $start Query start limit (for pagination)
834 * @param integer $number Query number returned (for pagination)
835 * @param array $filter_elements Array that contains elements to filter
836 * @return recordset/integer
838 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())
841 if (empty($form_code_types)) {
842 // Collect the active code types
843 $form_code_types = collect_codetypes("active", "array");
846 if ($count) {
847 //start the counter
848 $counter = 0;
849 } else {
850 // Figure out the appropriate limit clause
851 $limit_query = limit_query_string($limit, $start, $number);
853 // Prepare the sql bind array
854 $sql_bind_array = array();
856 // Start the query string
857 $query = "SELECT * FROM ((";
860 // Loop through each code type
861 $flag_first = true;
862 $flag_hit = false; //ensure there is a hit to avoid trying an empty query
863 foreach ($form_code_types as $form_code_type) {
864 // see if there is a hit
865 $mode_hit = null;
866 // only use the count method here, since it's much more efficient than doing the actual query
867 $mode_hit = sequential_code_set_search($form_code_type, $search_term, null, $modes, true, $active, null, null, $filter_elements, true);
868 if ($mode_hit) {
869 if ($count) {
870 // count the hits
871 $count_hits = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit);
872 // increment the counter
873 $counter += $count_hits;
874 } else {
875 $flag_hit = true;
876 // build the query
877 $return_query = code_set_search($form_code_type, $search_term, $count, $active, false, null, null, $filter_elements, null, $mode_hit, true);
878 if (!empty($sql_bind_array)) {
879 $sql_bind_array = array_merge($sql_bind_array, $return_query['binds']);
880 } else {
881 $sql_bind_array = $return_query['binds'];
884 if (!$flag_first) {
885 $query .= ") UNION ALL (";
888 $query .= $return_query['query'];
891 $flag_first = false;
895 if ($count) {
896 //return the count
897 return $counter;
898 } else {
899 // Finish the query string
900 $query .= ")) as atari $limit_query";
902 // Process and return the query (if there was a hit)
903 if ($flag_hit) {
904 return sqlStatement($query, $sql_bind_array);
910 * Returns the limit to be used in the sql query for code set searches.
912 * @param integer $limit Number of results to return (NULL means return all)
913 * @param integer $start Query start limit (for pagination)
914 * @param integer $number Query number returned (for pagination)
915 * @param boolean $return_only_one if true, then will only return one perfect matching item
916 * @return recordset/integer
918 function limit_query_string($limit = null, $start = null, $number = null, $return_only_one = false)
920 if (!is_null($start) && !is_null($number)) {
921 // For pagination of results
922 $limit_query = " LIMIT " . escape_limit($start) . ", " . escape_limit($number) . " ";
923 } elseif (!is_null($limit)) {
924 $limit_query = " LIMIT " . escape_limit($limit) . " ";
925 } else {
926 // No pagination and no limit
927 $limit_query = '';
930 if ($return_only_one) {
931 // Only return one result (this is where only matching for exact code match)
932 // Note this overrides the above limit settings
933 $limit_query = " LIMIT 1 ";
936 return $limit_query;