Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New external MDHT validation #5448

Merged
merged 2 commits into from
Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public function create_data($pid, $encounter, $sections, $components, $recipient
<postalCode>" . htmlspecialchars($representedOrganization['postalCode'] ?? '', ENT_QUOTES) . "</postalCode>
<country>" . htmlspecialchars($representedOrganization['country'] ?? '', ENT_QUOTES) . "</country>
</representedOrganization>";
$this->data .= "<referral_reason><text>" . htmlspecialchars($referral_reason, ENT_QUOTES) . "</text></referral_reason>";
$this->data .= "<referral_reason><text>" . htmlspecialchars($referral_reason ?: '', ENT_QUOTES) . "</text></referral_reason>";

/***************CCDA Header Information***************/
$this->data .= $this->getEncounterccdadispatchTable()->getPatientdata($pid, $encounter);
Expand Down
14 changes: 14 additions & 0 deletions library/globals.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -3509,6 +3509,20 @@ function gblTimeZones()
'',
xl('USPS Web Tools API Username')
),

'mdht_conformance_server_enable' => array(
xl('Use MDHT External Validation Service'),
'bool', // data type
'0',
xl('Enable CCDA conformance and validation API service')
),

'mdht_conformance_server' => array(
xl('CCDA MDHT Validation API Server Address'),
'text', // data type
'http://ccda.healthit.gov',
Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we assume the file will always have the /referenceccdaservice/ path? Or would it be better to specify the full server address here? That leaves the option for people to customize / change this if they never need it to.

Copy link
Sponsor Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all arguments are specific to this server.

xl('CCDA conformance and validation API service URL. Default is a public server mainly used for testing. Production sites should spin up your own.')
),
),

'Rx' => array(
Expand Down
122 changes: 120 additions & 2 deletions src/Services/Cda/CdaValidateDocuments.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,30 @@

namespace OpenEMR\Services\Cda;

use CURLFile;
use CURLStringFile;
use DOMDocument;
use Exception;
use OpenEMR\Common\Logging\SystemLogger;
use OpenEMR\Common\System\System;
use stdClass;

class CdaValidateDocuments
{
public $externalValidatorUrl;
public $externalValidatorEnabled;

public function __construct()
{
$this->externalValidatorEnabled = !empty($GLOBALS['mdht_conformance_server_enable'] ?? false);
$this->externalValidatorUrl = null;
if ($this->externalValidatorEnabled) {
$this->externalValidatorUrl = trim($GLOBALS['mdht_conformance_server'] ?? null) ?: 'http://ccda.healthit.gov';
Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does trim work on a null?

Copy link
Sponsor Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

if (!str_ends_with($this->externalValidatorUrl, '/')) {
$this->externalValidatorUrl .= '/';
}
$this->externalValidatorUrl .= 'referenceccdaservice/';
}
}

/**
Expand All @@ -30,14 +46,53 @@ public function __construct()
*/
public function validateDocument($document, $type)
{
// always validate schema XSD
$xsd = $this->validateXmlXsd($document, $type);
$schema_results = $this->validateSchematron($document, $type);
if ($this->externalValidatorEnabled) {
$schema_results = $this->ettValidateCcda($document);
} else {
$schema_results = $this->validateSchematron($document, $type);
}

$totals = array_merge($xsd, $schema_results);

return $totals;
}

/**
* @param $xml
* @return array|mixed
*/
public function ettValidateCcda($xml)
{
try {
$result = $this->ettValidateDocumentRequest($xml);
} catch (Exception $e) {
(new SystemLogger())->errorLogCaller($e->getMessage(), ["trace" => $e->getTraceAsString()]);
return [];
}
// translate result to our common render array
$results = array(
'errorCount' => $result['resultsMetaData']["resultMetaData"][0]["count"],
'warningCount' => 0,
'ignoredCount' => 0,
);
foreach ($result['ccdaValidationResults'] as $r) {
$results['errors'][] = array(
'type' => 'error',
'test' => $r['type'],
'description' => $r['description'],
'line' => $r['documentLineNumber'],
'path' => $r['xPath'],
'context' => $r['type'],
'xml' => '',
);
}
return $results;
}

/**
* @param string $port
* @return bool
* @throws Exception
*/
Expand Down Expand Up @@ -94,7 +149,7 @@ public function startValidationService($port = '6662'): bool
* @return mixed|null
* @throws Exception
*/
function schematronValidateDocument($xml, $type = 'ccda')
private function schematronValidateDocument($xml, $type = 'ccda')
{
$service = $this->startValidationService();
$reply = [];
Expand Down Expand Up @@ -123,6 +178,65 @@ function schematronValidateDocument($xml, $type = 'ccda')
return $reply;
}

/**
* @param $xml
* @return array|mixed
*/
private function ettValidateDocumentRequest($xml)
{
$reply = [];
if (empty($xml)) {
return $reply;
}

$headers = array(
"Content-Type: multipart/form-data",
"Accept: application/json",
);
$post_url = $this->externalValidatorUrl;
// I know there's a better way to do this but, not seeing it just now.
$post_file = $GLOBALS['temporary_files_dir'] . '/ccda.xml';
file_put_contents($post_file, $xml);
$file = new CURLFile($post_file, 'application/xhtml+xml', 'ccda.xml');

$post_this = [
'validationObjective' => 'C-CDA_IG_Plus_Vocab',
'referenceFileName' => 'noscenariofile',
'vocabularyConfig' => 'ccdaReferenceValidatorConfig',
'severityLevel' => 'ERROR',
'curesUpdate' => true,
'ccdaFile' => $file
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_this);

$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if (empty($response) || $status !== '200') {
$reply['resultsMetaData']["resultMetaData"][0]["count"] = 1;
$reply['ccdaValidationResults'][] = array(
'description' => xlt('Validation Request failed') .
': Error ' . (curl_error($ch) ?: xlt('Unknown')) . ' ' .
xlt('Request Status') . ':' . $status
);
}
curl_close($ch);
if ($status == '200') {
$reply = json_decode($response, true);
}

return $reply;
}

/**
* @param $document
* @param $type
Expand Down Expand Up @@ -191,6 +305,10 @@ private function formatXsdError($error): string
return $error_str;
}

/**
* @param $amid
* @return string
*/
public function createSchematronHtml($amid)
{
$errors = $this->fetchValidationLog($amid);
Expand Down