Commit generated changelog for 7.0.2.1 (#7458)
[openemr.git] / _rest_config.php
blobc1f652a315da9b3021c7c9f1547bfa2ed32e3e3a
1 <?php
3 /**
4 * Useful globals class for Rest
6 * @package OpenEMR
7 * @link http://www.open-emr.org
8 * @author Jerry Padgett <sjpadgett@gmail.com>
9 * @author Brady Miller <brady.g.miller@gmail.com>
10 * @copyright Copyright (c) 2018-2020 Jerry Padgett <sjpadgett@gmail.com>
11 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
12 * @copyright Copyright (c) 2024 Care Management Solutions, Inc. <stephen.waite@cmsvt.com>
13 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
16 require_once __DIR__ . '/vendor/autoload.php';
18 use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
19 use League\OAuth2\Server\Exception\OAuthServerException;
20 use League\OAuth2\Server\ResourceServer;
21 use Nyholm\Psr7\Factory\Psr17Factory;
22 use Nyholm\Psr7Server\ServerRequestCreator;
23 use OpenEMR\Common\Acl\AclMain;
24 use OpenEMR\Common\Auth\OpenIDConnect\Repositories\AccessTokenRepository;
25 use OpenEMR\Common\Http\HttpRestRequest;
26 use OpenEMR\Common\Logging\EventAuditLogger;
27 use OpenEMR\Common\Logging\SystemLogger;
28 use OpenEMR\Common\Session\SessionUtil;
29 use OpenEMR\FHIR\Config\ServerConfig;
30 use OpenEMR\Services\TrustedUserService;
31 use Psr\Http\Message\ResponseInterface;
32 use Psr\Http\Message\ServerRequestInterface;
35 // also a handy place to add utility methods
36 // TODO before v6 release: refactor http_response_code(); for psr responses.
38 class RestConfig
40 /** @var routemap is an array of patterns and routes */
41 public static $ROUTE_MAP;
43 /** @var fhir routemap is an of patterns and routes */
44 public static $FHIR_ROUTE_MAP;
46 /** @var portal routemap is an of patterns and routes */
47 public static $PORTAL_ROUTE_MAP;
49 /** @var app root is the root directory of the application */
50 public static $APP_ROOT;
52 /** @var root url of the application */
53 public static $ROOT_URL;
54 // you can guess what the rest are!
55 public static $VENDOR_DIR;
56 public static $SITE;
57 public static $apisBaseFullUrl;
58 public static $webserver_root;
59 public static $web_root;
60 public static $server_document_root;
61 public static $publicKey;
62 private static $INSTANCE;
63 private static $IS_INITIALIZED = false;
64 /** @var set to true if local api call */
65 private static $localCall = false;
66 /** @var set to true if not rest call */
67 private static $notRestCall = false;
69 /** prevents external construction */
70 private function __construct()
74 /**
75 * Returns an instance of the RestConfig singleton
77 * @return RestConfig
79 public static function GetInstance(): \RestConfig
81 if (!self::$IS_INITIALIZED) {
82 self::Init();
85 if (!self::$INSTANCE instanceof self) {
86 self::$INSTANCE = new self();
89 return self::$INSTANCE;
92 /**
93 * Initialize the RestConfig object
95 public static function Init(): void
97 if (self::$IS_INITIALIZED) {
98 return;
100 // The busy stuff.
101 self::setPaths();
102 self::setSiteFromEndpoint();
103 $serverConfig = new ServerConfig();
104 $serverConfig->setWebServerRoot(self::$webserver_root);
105 $serverConfig->setSiteId(self::$SITE);
106 self::$ROOT_URL = self::$web_root . "/apis";
107 self::$VENDOR_DIR = self::$webserver_root . "/vendor";
108 self::$publicKey = $serverConfig->getPublicRestKey();
109 self::$IS_INITIALIZED = true;
113 * Basic paths when GLOBALS are not yet available.
115 * @return void
117 private static function SetPaths(): void
119 $isWindows = (stripos(PHP_OS_FAMILY, 'WIN') === 0);
120 // careful if moving this class to modify where's root.
121 self::$webserver_root = __DIR__;
122 if ($isWindows) {
123 //convert windows path separators
124 self::$webserver_root = str_replace("\\", "/", self::$webserver_root);
126 // Collect the apache server document root (and convert to windows slashes, if needed)
127 self::$server_document_root = realpath($_SERVER['DOCUMENT_ROOT']);
128 if ($isWindows) {
129 //convert windows path separators
130 self::$server_document_root = str_replace("\\", "/", self::$server_document_root);
132 self::$web_root = substr(self::$webserver_root, strspn(self::$webserver_root ^ self::$server_document_root, "\0"));
133 // Ensure web_root starts with a path separator
134 if (preg_match("/^[^\/]/", self::$web_root)) {
135 self::$web_root = "/" . self::$web_root;
137 // Will need these occasionally. sql init comes to mind!
138 $GLOBALS['rootdir'] = self::$web_root . "/interface";
139 // Absolute path to the source code include and headers file directory (Full path):
140 $GLOBALS['srcdir'] = self::$webserver_root . "/library";
141 // Absolute path to the location of documentroot directory for use with include statements:
142 $GLOBALS['fileroot'] = self::$webserver_root;
143 // Absolute path to the location of interface directory for use with include statements:
144 $GLOBALS['incdir'] = self::$webserver_root . "/interface";
145 // Absolute path to the location of documentroot directory for use with include statements:
146 $GLOBALS['webroot'] = self::$web_root;
147 // Static assets directory, relative to the webserver root.
148 $GLOBALS['assets_static_relative'] = self::$web_root . "/public/assets";
149 // Relative themes directory, relative to the webserver root.
150 $GLOBALS['themes_static_relative'] = self::$web_root . "/public/themes";
151 // Relative images directory, relative to the webserver root.
152 $GLOBALS['images_static_relative'] = self::$web_root . "/public/images";
153 // Static images directory, absolute to the webserver root.
154 $GLOBALS['images_static_absolute'] = self::$webserver_root . "/public/images";
155 //Composer vendor directory, absolute to the webserver root.
156 $GLOBALS['vendor_dir'] = self::$webserver_root . "/vendor";
159 private static function setSiteFromEndpoint(): void
161 // Get site from endpoint if available. Unsure about this though!
162 // Will fail during sql init otherwise.
163 $endPointParts = self::parseEndPoint(self::getRequestEndPoint());
164 if (count($endPointParts) > 1) {
165 $site_id = $endPointParts[0] ?? '';
166 if ($site_id) {
167 self::$SITE = $site_id;
172 public static function parseEndPoint($resource): array
174 if ($resource[0] === '/') {
175 $resource = substr($resource, 1);
177 return explode('/', $resource);
180 public static function getRequestEndPoint(): string
182 $resource = null;
183 if (!empty($_REQUEST['_REWRITE_COMMAND'])) {
184 $resource = "/" . $_REQUEST['_REWRITE_COMMAND'];
185 } elseif (!empty($_SERVER['REDIRECT_QUERY_STRING'])) {
186 $resource = str_replace('_REWRITE_COMMAND=', '/', $_SERVER['REDIRECT_QUERY_STRING']);
187 } else {
188 if (!empty($_SERVER['REQUEST_URI'])) {
189 if (strpos($_SERVER['REQUEST_URI'], '?') > 0) {
190 $resource = strstr($_SERVER['REQUEST_URI'], '?', true);
191 } else {
192 $resource = str_replace(self::$ROOT_URL ?? '', '', $_SERVER['REQUEST_URI']);
197 return $resource;
200 public static function verifyAccessToken()
202 $logger = new SystemLogger();
203 $response = self::createServerResponse();
204 $request = self::createServerRequest();
205 $server = new ResourceServer(
206 new AccessTokenRepository(),
207 self::$publicKey
209 try {
210 $raw = $server->validateAuthenticatedRequest($request);
211 } catch (OAuthServerException $exception) {
212 $logger->error("RestConfig->verifyAccessToken() OAuthServerException", ["message" => $exception->getMessage()]);
213 return $exception->generateHttpResponse($response);
214 } catch (\Exception $exception) {
215 $logger->error("RestConfig->verifyAccessToken() Exception", ["message" => $exception->getMessage()]);
216 return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))
217 ->generateHttpResponse($response);
220 return $raw;
224 * Returns true if the access token for the given token id is valid. Otherwise returns the access denied response.
225 * @param $tokenId
226 * @return bool|ResponseInterface
228 public static function validateAccessTokenRevoked($tokenId)
230 $repository = new AccessTokenRepository();
231 if ($repository->isAccessTokenRevokedInDatabase($tokenId)) {
232 $response = self::createServerResponse();
233 return OAuthServerException::accessDenied('Access token has been revoked')->generateHttpResponse($response);
235 return true;
238 public static function isTrustedUser($clientId, $userId)
240 $trustedUserService = new TrustedUserService();
241 $response = self::createServerResponse();
242 try {
243 if (!$trustedUserService->isTrustedUser($clientId, $userId)) {
244 (new SystemLogger())->debug(
245 "invalid Trusted User. Refresh Token revoked or logged out",
246 ['clientId' => $clientId, 'userId' => $userId]
248 throw new OAuthServerException('Refresh Token revoked or logged out', 0, 'invalid _request', 400);
250 return $trustedUserService->getTrustedUser($clientId, $userId);
251 } catch (OAuthServerException $exception) {
252 return $exception->generateHttpResponse($response);
253 } catch (\Exception $exception) {
254 return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))
255 ->generateHttpResponse($response);
259 public static function createServerResponse(): ResponseInterface
261 $psr17Factory = new Psr17Factory();
263 return $psr17Factory->createResponse();
266 public static function createServerRequest(): ServerRequestInterface
268 $psr17Factory = new Psr17Factory();
269 $creator = new ServerRequestCreator(
270 $psr17Factory, // ServerRequestFactory
271 $psr17Factory, // UriFactory
272 $psr17Factory, // UploadedFileFactory
273 $psr17Factory // StreamFactory
276 return $creator->fromGlobals();
279 public static function destroySession(): void
281 SessionUtil::apiSessionCookieDestroy();
284 public static function getPostData($data)
286 if (count($_POST)) {
287 return $_POST;
290 if ($post_data = file_get_contents('php://input')) {
291 if ($post_json = json_decode($post_data, true)) {
292 return $post_json;
294 parse_str($post_data, $post_variables);
295 if (count($post_variables)) {
296 return $post_variables;
300 return null;
303 public static function authorization_check($section, $value, $user = '', $aclPermission = ''): void
305 $result = AclMain::aclCheckCore($section, $value, $user, $aclPermission);
306 if (!$result) {
307 if (!self::$notRestCall) {
308 http_response_code(401);
310 exit();
314 // Main function to check scope
315 // Use cases:
316 // Only sending $scopeType would be for something like 'openid'
317 // For using all 3 parameters would be for something like 'user/Organization.write'
318 // $scopeType = 'user', $resource = 'Organization', $permission = 'write'
319 public static function scope_check($scopeType, $resource = null, $permission = null): void
321 if (!empty($GLOBALS['oauth_scopes'])) {
322 // Need to ensure has scope
323 if (empty($resource)) {
324 // Simply check to see if $scopeType is an allowed scope
325 $scope = $scopeType;
326 } else {
327 // Resource scope check
328 $scope = $scopeType . '/' . $resource . '.' . $permission;
330 if (!in_array($scope, $GLOBALS['oauth_scopes'])) {
331 (new SystemLogger())->debug("RestConfig::scope_check scope not in access token", ['scope' => $scope, 'scopes_granted' => $GLOBALS['oauth_scopes']]);
332 http_response_code(401);
333 exit;
335 } else {
336 (new SystemLogger())->error("RestConfig::scope_check global scope array is empty");
337 http_response_code(401);
338 exit;
342 public static function setLocalCall(): void
344 self::$localCall = true;
347 public static function setNotRestCall(): void
349 self::$notRestCall = true;
352 public static function is_fhir_request($resource): bool
354 return stripos(strtolower($resource), "/fhir/") !== false;
357 public static function is_portal_request($resource): bool
359 return stripos(strtolower($resource), "/portal/") !== false;
362 public static function is_api_request($resource): bool
364 return stripos(strtolower($resource), "/api/") !== false;
367 public static function skipApiAuth($resource): bool
369 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
370 // we don't authenticate OPTIONS requests
371 return true;
374 // ensure 1) sane site and 2) ensure the site exists on filesystem before even considering for skip api auth
375 if (empty(self::$SITE) || preg_match('/[^A-Za-z0-9\\-.]/', self::$SITE) || !file_exists(__DIR__ . '/sites/' . self::$SITE)) {
376 error_log("OpenEMR Error - api site error, so forced exit");
377 http_response_code(400);
378 exit();
380 // let the capability statement for FHIR or the SMART-on-FHIR through
381 $resource = str_replace('/' . self::$SITE, '', $resource);
382 if (
383 // TODO: @adunsulag we need to centralize our auth skipping logic... as we have this duplicated in HttpRestRouteHandler
384 // however, at the point of this method we don't have the resource identified and haven't gone through our parsing
385 // routine to handle that logic...
386 $resource === ("/fhir/metadata") ||
387 $resource === ("/fhir/.well-known/smart-configuration") ||
388 // skip list and single instance routes
389 0 === strpos("/fhir/OperationDefinition", $resource)
391 return true;
392 } else {
393 return false;
397 public static function apiLog($response = '', $requestBody = ''): void
399 $logResponse = $response;
401 // only log when using standard api calls (skip when using local api calls from within OpenEMR)
402 // and when api log option is set
403 if (!$GLOBALS['is_local_api'] && !self::$notRestCall && $GLOBALS['api_log_option']) {
404 if ($GLOBALS['api_log_option'] == 1) {
405 // Do not log the response and requestBody
406 $logResponse = '';
407 $requestBody = '';
409 if ($response instanceof ResponseInterface) {
410 if (self::shouldLogResponse($response)) {
411 $body = $response->getBody();
412 $logResponse = $body->getContents();
413 $body->rewind();
414 } else {
415 $logResponse = 'Content not application/json - Skip binary data';
417 } else {
418 $logResponse = (!empty($logResponse)) ? json_encode($response) : '';
421 // convert pertinent elements to json
422 $requestBody = (!empty($requestBody)) ? json_encode($requestBody) : '';
424 // prepare values and call the log function
425 $event = 'api';
426 $category = 'api';
427 $method = $_SERVER['REQUEST_METHOD'];
428 $url = $_SERVER['REQUEST_URI'];
429 $patientId = (int)($_SESSION['pid'] ?? 0);
430 $userId = (int)($_SESSION['authUserID'] ?? 0);
431 $api = [
432 'user_id' => $userId,
433 'patient_id' => $patientId,
434 'method' => $method,
435 'request' => $GLOBALS['resource'],
436 'request_url' => $url,
437 'request_body' => $requestBody,
438 'response' => $logResponse
440 if ($patientId === 0) {
441 $patientId = null; //entries in log table are blank for no patient_id, whereas in api_log are 0, which is why above $api value uses 0 when empty
443 EventAuditLogger::instance()->recordLogItem(1, $event, ($_SESSION['authUser'] ?? ''), ($_SESSION['authProvider'] ?? ''), 'api log', $patientId, $category, 'open-emr', null, null, '', $api);
447 public static function emitResponse($response, $build = false): void
449 if (headers_sent()) {
450 throw new RuntimeException('Headers already sent.');
452 $statusLine = sprintf(
453 'HTTP/%s %s %s',
454 $response->getProtocolVersion(),
455 $response->getStatusCode(),
456 $response->getReasonPhrase()
458 header($statusLine, true);
459 foreach ($response->getHeaders() as $name => $values) {
460 $responseHeader = sprintf('%s: %s', $name, $response->getHeaderLine($name));
461 header($responseHeader, false);
463 echo $response->getBody();
467 * If the FHIR System scopes enabled or not. True if its turned on, false otherwise.
468 * @return bool
470 public static function areSystemScopesEnabled()
472 return $GLOBALS['rest_system_scopes_api'] === '1';
475 public function authenticateUserToken($tokenId, $clientId, $userId): bool
477 $ip = collectIpAddresses();
479 // check for token
480 $accessTokenRepo = new AccessTokenRepository();
481 $authTokenExpiration = $accessTokenRepo->getTokenExpiration($tokenId, $clientId, $userId);
483 if (empty($authTokenExpiration)) {
484 EventAuditLogger::instance()->newEvent('api', '', '', 0, "API failure: " . $ip['ip_string'] . ". Token not found for client[" . $clientId . "] and user " . $userId . ".");
485 return false;
488 // Ensure token not expired (note an expired token should have already been caught by oauth2, however will also check here)
489 $currentDateTime = date("Y-m-d H:i:s");
490 $expiryDateTime = date("Y-m-d H:i:s", strtotime($authTokenExpiration));
491 if ($expiryDateTime <= $currentDateTime) {
492 EventAuditLogger::instance()->newEvent('api', '', '', 0, "API failure: " . $ip['ip_string'] . ". Token expired for client[" . $clientId . "] and user " . $userId . ".");
493 return false;
496 // Token authentication passed
497 EventAuditLogger::instance()->newEvent('api', '', '', 1, "API success: " . $ip['ip_string'] . ". Token successfully used for client[" . $clientId . "] and user " . $userId . ".");
498 return true;
502 * Checks if we should log the response interface (we don't want to log binary documents or anything like that)
503 * We only log requests with a content-type of any form of json fhir+application/json or application/json
504 * @param ResponseInterface $response
505 * @return bool If the request should be logged, false otherwise
507 private static function shouldLogResponse(ResponseInterface $response)
509 if ($response->hasHeader("Content-Type")) {
510 $contentType = $response->getHeaderLine("Content-Type");
511 if ($contentType === 'application/json') {
512 return true;
516 return false;
520 * Grabs all of the context information for the request's access token and populates any context variables the
521 * request needs (such as patient binding information). Returns the populated request
522 * @param HttpRestRequest $restRequest
523 * @return HttpRestRequest
525 public function populateTokenContextForRequest(HttpRestRequest $restRequest)
528 $context = $this->getTokenContextForRequest($restRequest);
529 // note that the context here is the SMART value that is returned in the response for an AccessToken in this
530 // case it is the patient value which is the logical id (ie uuid) of the patient.
531 $patientUuid = $context['patient'] ?? null;
532 if (!empty($patientUuid)) {
533 // we only set the bound patient access if the underlying user can still access the patient
534 if ($this->checkUserHasAccessToPatient($restRequest->getRequestUserId(), $patientUuid)) {
535 $restRequest->setPatientUuidString($patientUuid);
536 } else {
537 (new SystemLogger())->error("OpenEMR Error: api had patient launch scope but user did not have access to patient uuid."
538 . " Resources restricted with patient scopes will not return results");
540 } else {
541 (new SystemLogger())->error("OpenEMR Error: api had patient launch scope but no patient was set in the "
542 . " session cache. Resources restricted with patient scopes will not return results");
544 return $restRequest;
547 public function getTokenContextForRequest(HttpRestRequest $restRequest)
549 $accessTokenRepo = new AccessTokenRepository();
550 // note this is pretty confusing as getAccessTokenId comes from the oauth_access_id which is the token NOT
551 // the database id even though this is called accessTokenId....
552 $token = $accessTokenRepo->getTokenByToken($restRequest->getAccessTokenId());
553 $context = $token['context'] ?? "{}"; // if there is no populated context we just return an empty return
554 try {
555 return json_decode($context, true);
556 } catch (\Exception $exception) {
557 (new SystemLogger())->error("OpenEMR Error: failed to decode token context json", ['exception' => $exception->getMessage()
558 , 'tokenId' => $restRequest->getAccessTokenId()]);
560 return [];
565 * Checks whether a user has access to the patient. Returns true if the user can access the given patient, false otherwise
566 * @param $userId The id from the users table that represents the user
567 * @param $patientUuid The uuid from the patient_data table that represents the patient
568 * @return bool True if has access, false otherwise
570 private function checkUserHasAccessToPatient($userId, $patientUuid)
572 // TODO: the session should never be populated with the pid from the access token unless the user had access to
573 // it. However, if we wanted an additional check or if we wanted to fire off any kind of event that does
574 // patient filtering by provider / clinic we would handle that here.
575 return true;
579 /** prevents external cloning */
580 private function __clone()
585 // Include our routes and init routes global
587 require_once(__DIR__ . "/_rest_routes.inc.php");