prep master for 7.0.2-dev (#6331)
[openemr.git] / _rest_config.php
blob602730739366b4edd6267b2496cbd0d02564205a
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 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
15 require_once __DIR__ . '/vendor/autoload.php';
17 use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
18 use League\OAuth2\Server\Exception\OAuthServerException;
19 use League\OAuth2\Server\ResourceServer;
20 use Nyholm\Psr7\Factory\Psr17Factory;
21 use Nyholm\Psr7Server\ServerRequestCreator;
22 use OpenEMR\Common\Acl\AclMain;
23 use OpenEMR\Common\Auth\OpenIDConnect\Repositories\AccessTokenRepository;
24 use OpenEMR\Common\Http\HttpRestRequest;
25 use OpenEMR\Common\Logging\EventAuditLogger;
26 use OpenEMR\Common\Logging\SystemLogger;
27 use OpenEMR\Common\Session\SessionUtil;
28 use OpenEMR\Services\TrustedUserService;
29 use Psr\Http\Message\ResponseInterface;
30 use Psr\Http\Message\ServerRequestInterface;
33 // also a handy place to add utility methods
34 // TODO before v6 release: refactor http_response_code(); for psr responses.
36 class RestConfig
38 /** @var routemap is an array of patterns and routes */
39 public static $ROUTE_MAP;
41 /** @var fhir routemap is an of patterns and routes */
42 public static $FHIR_ROUTE_MAP;
44 /** @var portal routemap is an of patterns and routes */
45 public static $PORTAL_ROUTE_MAP;
47 /** @var app root is the root directory of the application */
48 public static $APP_ROOT;
50 /** @var root url of the application */
51 public static $ROOT_URL;
52 // you can guess what the rest are!
53 public static $VENDOR_DIR;
54 public static $SITE;
55 public static $apisBaseFullUrl;
56 public static $webserver_root;
57 public static $web_root;
58 public static $server_document_root;
59 public static $publicKey;
60 private static $INSTANCE;
61 private static $IS_INITIALIZED = false;
62 /** @var set to true if local api call */
63 private static $localCall = false;
64 /** @var set to true if not rest call */
65 private static $notRestCall = false;
67 /** prevents external construction */
68 private function __construct()
72 /**
73 * Returns an instance of the RestConfig singleton
75 * @return RestConfig
77 public static function GetInstance(): \RestConfig
79 if (!self::$IS_INITIALIZED) {
80 self::Init();
83 if (!self::$INSTANCE instanceof self) {
84 self::$INSTANCE = new self();
87 return self::$INSTANCE;
90 /**
91 * Initialize the RestConfig object
93 public static function Init(): void
95 if (self::$IS_INITIALIZED) {
96 return;
98 // The busy stuff.
99 self::setPaths();
100 self::setSiteFromEndpoint();
101 self::$ROOT_URL = self::$web_root . "/apis";
102 self::$VENDOR_DIR = self::$webserver_root . "/vendor";
103 self::$publicKey = self::$webserver_root . "/sites/" . self::$SITE . "/documents/certificates/oapublic.key";
104 self::$IS_INITIALIZED = true;
108 * Basic paths when GLOBALS are not yet available.
110 * @return void
112 private static function SetPaths(): void
114 $isWindows = (stripos(PHP_OS_FAMILY, 'WIN') === 0);
115 // careful if moving this class to modify where's root.
116 self::$webserver_root = __DIR__;
117 if ($isWindows) {
118 //convert windows path separators
119 self::$webserver_root = str_replace("\\", "/", self::$webserver_root);
121 // Collect the apache server document root (and convert to windows slashes, if needed)
122 self::$server_document_root = realpath($_SERVER['DOCUMENT_ROOT']);
123 if ($isWindows) {
124 //convert windows path separators
125 self::$server_document_root = str_replace("\\", "/", self::$server_document_root);
127 self::$web_root = substr(self::$webserver_root, strspn(self::$webserver_root ^ self::$server_document_root, "\0"));
128 // Ensure web_root starts with a path separator
129 if (preg_match("/^[^\/]/", self::$web_root)) {
130 self::$web_root = "/" . self::$web_root;
132 // Will need these occasionally. sql init comes to mind!
133 $GLOBALS['rootdir'] = self::$web_root . "/interface";
134 // Absolute path to the source code include and headers file directory (Full path):
135 $GLOBALS['srcdir'] = self::$webserver_root . "/library";
136 // Absolute path to the location of documentroot directory for use with include statements:
137 $GLOBALS['fileroot'] = self::$webserver_root;
138 // Absolute path to the location of interface directory for use with include statements:
139 $GLOBALS['incdir'] = self::$webserver_root . "/interface";
140 // Absolute path to the location of documentroot directory for use with include statements:
141 $GLOBALS['webroot'] = self::$web_root;
142 // Static assets directory, relative to the webserver root.
143 $GLOBALS['assets_static_relative'] = self::$web_root . "/public/assets";
144 // Relative themes directory, relative to the webserver root.
145 $GLOBALS['themes_static_relative'] = self::$web_root . "/public/themes";
146 // Relative images directory, relative to the webserver root.
147 $GLOBALS['images_static_relative'] = self::$web_root . "/public/images";
148 // Static images directory, absolute to the webserver root.
149 $GLOBALS['images_static_absolute'] = self::$webserver_root . "/public/images";
150 //Composer vendor directory, absolute to the webserver root.
151 $GLOBALS['vendor_dir'] = self::$webserver_root . "/vendor";
154 private static function setSiteFromEndpoint(): void
156 // Get site from endpoint if available. Unsure about this though!
157 // Will fail during sql init otherwise.
158 $endPointParts = self::parseEndPoint(self::getRequestEndPoint());
159 if (count($endPointParts) > 1) {
160 $site_id = $endPointParts[0] ?? '';
161 if ($site_id) {
162 self::$SITE = $site_id;
167 public static function parseEndPoint($resource): array
169 if ($resource[0] === '/') {
170 $resource = substr($resource, 1);
172 return explode('/', $resource);
175 public static function getRequestEndPoint(): string
177 $resource = null;
178 if (!empty($_REQUEST['_REWRITE_COMMAND'])) {
179 $resource = "/" . $_REQUEST['_REWRITE_COMMAND'];
180 } elseif (!empty($_SERVER['REDIRECT_QUERY_STRING'])) {
181 $resource = str_replace('_REWRITE_COMMAND=', '/', $_SERVER['REDIRECT_QUERY_STRING']);
182 } else {
183 if (!empty($_SERVER['REQUEST_URI'])) {
184 if (strpos($_SERVER['REQUEST_URI'], '?') > 0) {
185 $resource = strstr($_SERVER['REQUEST_URI'], '?', true);
186 } else {
187 $resource = str_replace(self::$ROOT_URL ?? '', '', $_SERVER['REQUEST_URI']);
192 return $resource;
195 public static function verifyAccessToken()
197 $logger = new SystemLogger();
198 $response = self::createServerResponse();
199 $request = self::createServerRequest();
200 $server = new ResourceServer(
201 new AccessTokenRepository(),
202 self::$publicKey
204 try {
205 $raw = $server->validateAuthenticatedRequest($request);
206 } catch (OAuthServerException $exception) {
207 $logger->error("RestConfig->verifyAccessToken() OAuthServerException", ["message" => $exception->getMessage()]);
208 return $exception->generateHttpResponse($response);
209 } catch (\Exception $exception) {
210 $logger->error("RestConfig->verifyAccessToken() Exception", ["message" => $exception->getMessage()]);
211 return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))
212 ->generateHttpResponse($response);
215 return $raw;
219 * Returns true if the access token for the given token id is valid. Otherwise returns the access denied response.
220 * @param $tokenId
221 * @return bool|ResponseInterface
223 public static function validateAccessTokenRevoked($tokenId)
225 $repository = new AccessTokenRepository();
226 if ($repository->isAccessTokenRevokedInDatabase($tokenId)) {
227 $response = self::createServerResponse();
228 return OAuthServerException::accessDenied('Access token has been revoked')->generateHttpResponse($response);
230 return true;
233 public static function isTrustedUser($clientId, $userId)
235 $trustedUserService = new TrustedUserService();
236 $response = self::createServerResponse();
237 try {
238 if (!$trustedUserService->isTrustedUser($clientId, $userId)) {
239 (new SystemLogger())->debug(
240 "invalid Trusted User. Refresh Token revoked or logged out",
241 ['clientId' => $clientId, 'userId' => $userId]
243 throw new OAuthServerException('Refresh Token revoked or logged out', 0, 'invalid _request', 400);
245 return $trustedUserService->getTrustedUser($clientId, $userId);
246 } catch (OAuthServerException $exception) {
247 return $exception->generateHttpResponse($response);
248 } catch (\Exception $exception) {
249 return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))
250 ->generateHttpResponse($response);
254 public static function createServerResponse(): ResponseInterface
256 $psr17Factory = new Psr17Factory();
258 return $psr17Factory->createResponse();
261 public static function createServerRequest(): ServerRequestInterface
263 $psr17Factory = new Psr17Factory();
264 $creator = new ServerRequestCreator(
265 $psr17Factory, // ServerRequestFactory
266 $psr17Factory, // UriFactory
267 $psr17Factory, // UploadedFileFactory
268 $psr17Factory // StreamFactory
271 return $creator->fromGlobals();
274 public static function destroySession(): void
276 SessionUtil::apiSessionCookieDestroy();
279 public static function getPostData($data)
281 if (count($_POST)) {
282 return $_POST;
285 if ($post_data = file_get_contents('php://input')) {
286 if ($post_json = json_decode($post_data, true)) {
287 return $post_json;
289 parse_str($post_data, $post_variables);
290 if (count($post_variables)) {
291 return $post_variables;
295 return null;
298 public static function authorization_check($section, $value, $user = ''): void
300 $result = AclMain::aclCheckCore($section, $value, $user);
301 if (!$result) {
302 if (!self::$notRestCall) {
303 http_response_code(401);
305 exit();
309 // Main function to check scope
310 // Use cases:
311 // Only sending $scopeType would be for something like 'openid'
312 // For using all 3 parameters would be for something like 'user/Organization.write'
313 // $scopeType = 'user', $resource = 'Organization', $permission = 'write'
314 public static function scope_check($scopeType, $resource = null, $permission = null): void
316 if (!empty($GLOBALS['oauth_scopes'])) {
317 // Need to ensure has scope
318 if (empty($resource)) {
319 // Simply check to see if $scopeType is an allowed scope
320 $scope = $scopeType;
321 } else {
322 // Resource scope check
323 $scope = $scopeType . '/' . $resource . '.' . $permission;
325 if (!in_array($scope, $GLOBALS['oauth_scopes'])) {
326 (new SystemLogger())->debug("RestConfig::scope_check scope not in access token", ['scope' => $scope, 'scopes_granted' => $GLOBALS['oauth_scopes']]);
327 http_response_code(401);
328 exit;
330 } else {
331 (new SystemLogger())->error("RestConfig::scope_check global scope array is empty");
332 http_response_code(401);
333 exit;
337 public static function setLocalCall(): void
339 self::$localCall = true;
342 public static function setNotRestCall(): void
344 self::$notRestCall = true;
347 public static function is_fhir_request($resource): bool
349 return stripos(strtolower($resource), "/fhir/") !== false;
352 public static function is_portal_request($resource): bool
354 return stripos(strtolower($resource), "/portal/") !== false;
357 public static function is_api_request($resource): bool
359 return stripos(strtolower($resource), "/api/") !== false;
362 public static function skipApiAuth($resource): bool
364 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
365 // we don't authenticate OPTIONS requests
366 return true;
369 // ensure 1) sane site and 2) ensure the site exists on filesystem before even considering for skip api auth
370 if (empty(self::$SITE) || preg_match('/[^A-Za-z0-9\\-.]/', self::$SITE) || !file_exists(__DIR__ . '/sites/' . self::$SITE)) {
371 error_log("OpenEMR Error - api site error, so forced exit");
372 http_response_code(400);
373 exit();
375 // let the capability statement for FHIR or the SMART-on-FHIR through
376 $resource = str_replace('/' . self::$SITE, '', $resource);
377 if (
378 // TODO: @adunsulag we need to centralize our auth skipping logic... as we have this duplicated in HttpRestRouteHandler
379 // however, at the point of this method we don't have the resource identified and haven't gone through our parsing
380 // routine to handle that logic...
381 $resource === ("/fhir/metadata") ||
382 $resource === ("/fhir/.well-known/smart-configuration") ||
383 // skip list and single instance routes
384 0 === strpos("/fhir/OperationDefinition", $resource)
386 return true;
387 } else {
388 return false;
392 public static function apiLog($response = '', $requestBody = ''): void
394 $logResponse = $response;
396 // only log when using standard api calls (skip when using local api calls from within OpenEMR)
397 // and when api log option is set
398 if (!$GLOBALS['is_local_api'] && !self::$notRestCall && $GLOBALS['api_log_option']) {
399 if ($GLOBALS['api_log_option'] == 1) {
400 // Do not log the response and requestBody
401 $logResponse = '';
402 $requestBody = '';
404 if ($response instanceof ResponseInterface) {
405 if (self::shouldLogResponse($response)) {
406 $body = $response->getBody();
407 $logResponse = $body->getContents();
408 $body->rewind();
409 } else {
410 $logResponse = 'Content not application/json - Skip binary data';
412 } else {
413 $logResponse = (!empty($logResponse)) ? json_encode($response) : '';
416 // convert pertinent elements to json
417 $requestBody = (!empty($requestBody)) ? json_encode($requestBody) : '';
419 // prepare values and call the log function
420 $event = 'api';
421 $category = 'api';
422 $method = $_SERVER['REQUEST_METHOD'];
423 $url = $_SERVER['REQUEST_URI'];
424 $patientId = (int)($_SESSION['pid'] ?? 0);
425 $userId = (int)($_SESSION['authUserID'] ?? 0);
426 $api = [
427 'user_id' => $userId,
428 'patient_id' => $patientId,
429 'method' => $method,
430 'request' => $GLOBALS['resource'],
431 'request_url' => $url,
432 'request_body' => $requestBody,
433 'response' => $logResponse
435 if ($patientId === 0) {
436 $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
438 EventAuditLogger::instance()->recordLogItem(1, $event, ($_SESSION['authUser'] ?? ''), ($_SESSION['authProvider'] ?? ''), 'api log', $patientId, $category, 'open-emr', null, null, '', $api);
442 public static function emitResponse($response, $build = false): void
444 if (headers_sent()) {
445 throw new RuntimeException('Headers already sent.');
447 $statusLine = sprintf(
448 'HTTP/%s %s %s',
449 $response->getProtocolVersion(),
450 $response->getStatusCode(),
451 $response->getReasonPhrase()
453 header($statusLine, true);
454 foreach ($response->getHeaders() as $name => $values) {
455 $responseHeader = sprintf('%s: %s', $name, $response->getHeaderLine($name));
456 header($responseHeader, false);
458 echo $response->getBody();
462 * If the FHIR System scopes enabled or not. True if its turned on, false otherwise.
463 * @return bool
465 public static function areSystemScopesEnabled()
467 return $GLOBALS['rest_system_scopes_api'] === '1';
470 public function authenticateUserToken($tokenId, $clientId, $userId): bool
472 $ip = collectIpAddresses();
474 // check for token
475 $accessTokenRepo = new AccessTokenRepository();
476 $authTokenExpiration = $accessTokenRepo->getTokenExpiration($tokenId, $clientId, $userId);
478 if (empty($authTokenExpiration)) {
479 EventAuditLogger::instance()->newEvent('api', '', '', 0, "API failure: " . $ip['ip_string'] . ". Token not found for client[" . $clientId . "] and user " . $userId . ".");
480 return false;
483 // Ensure token not expired (note an expired token should have already been caught by oauth2, however will also check here)
484 $currentDateTime = date("Y-m-d H:i:s");
485 $expiryDateTime = date("Y-m-d H:i:s", strtotime($authTokenExpiration));
486 if ($expiryDateTime <= $currentDateTime) {
487 EventAuditLogger::instance()->newEvent('api', '', '', 0, "API failure: " . $ip['ip_string'] . ". Token expired for client[" . $clientId . "] and user " . $userId . ".");
488 return false;
491 // Token authentication passed
492 EventAuditLogger::instance()->newEvent('api', '', '', 1, "API success: " . $ip['ip_string'] . ". Token successfully used for client[" . $clientId . "] and user " . $userId . ".");
493 return true;
497 * Checks if we should log the response interface (we don't want to log binary documents or anything like that)
498 * We only log requests with a content-type of any form of json fhir+application/json or application/json
499 * @param ResponseInterface $response
500 * @return bool If the request should be logged, false otherwise
502 private static function shouldLogResponse(ResponseInterface $response)
504 if ($response->hasHeader("Content-Type")) {
505 $contentType = $response->getHeaderLine("Content-Type");
506 if ($contentType === 'application/json') {
507 return true;
511 return false;
515 * Grabs all of the context information for the request's access token and populates any context variables the
516 * request needs (such as patient binding information). Returns the populated request
517 * @param HttpRestRequest $restRequest
518 * @return HttpRestRequest
520 public function populateTokenContextForRequest(HttpRestRequest $restRequest)
523 $context = $this->getTokenContextForRequest($restRequest);
524 // note that the context here is the SMART value that is returned in the response for an AccessToken in this
525 // case it is the patient value which is the logical id (ie uuid) of the patient.
526 $patientUuid = $context['patient'] ?? null;
527 if (!empty($patientUuid)) {
528 // we only set the bound patient access if the underlying user can still access the patient
529 if ($this->checkUserHasAccessToPatient($restRequest->getRequestUserId(), $patientUuid)) {
530 $restRequest->setPatientUuidString($patientUuid);
531 } else {
532 (new SystemLogger())->error("OpenEMR Error: api had patient launch scope but user did not have access to patient uuid."
533 . " Resources restricted with patient scopes will not return results");
535 } else {
536 (new SystemLogger())->error("OpenEMR Error: api had patient launch scope but no patient was set in the "
537 . " session cache. Resources restricted with patient scopes will not return results");
539 return $restRequest;
542 public function getTokenContextForRequest(HttpRestRequest $restRequest)
544 $accessTokenRepo = new AccessTokenRepository();
545 // note this is pretty confusing as getAccessTokenId comes from the oauth_access_id which is the token NOT
546 // the database id even though this is called accessTokenId....
547 $token = $accessTokenRepo->getTokenByToken($restRequest->getAccessTokenId());
548 $context = $token['context'] ?? "{}"; // if there is no populated context we just return an empty return
549 try {
550 return json_decode($context, true);
551 } catch (\Exception $exception) {
552 (new SystemLogger())->error("OpenEMR Error: failed to decode token context json", ['exception' => $exception->getMessage()
553 , 'tokenId' => $restRequest->getAccessTokenId()]);
555 return [];
560 * Checks whether a user has access to the patient. Returns true if the user can access the given patient, false otherwise
561 * @param $userId The id from the users table that represents the user
562 * @param $patientUuid The uuid from the patient_data table that represents the patient
563 * @return bool True if has access, false otherwise
565 private function checkUserHasAccessToPatient($userId, $patientUuid)
567 // TODO: the session should never be populated with the pid from the access token unless the user had access to
568 // it. However, if we wanted an additional check or if we wanted to fire off any kind of event that does
569 // patient filtering by provider / clinic we would handle that here.
570 return true;
574 /** prevents external cloning */
575 private function __clone()
580 // Include our routes and init routes global
582 require_once(__DIR__ . "/_rest_routes.inc.php");