Openemr fixes #5215 bulk export provenance, fixes #5216 api docs (#5217)
[openemr.git] / _rest_config.php
blob08a7f3b496649e9d9ec79a424e66a69f44699f0f
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 if (
377 $resource === ("/" . self::$SITE . "/fhir/metadata") ||
378 $resource === ("/" . self::$SITE . "/fhir/.well-known/smart-configuration")
380 return true;
381 } else {
382 return false;
386 public static function apiLog($response = '', $requestBody = ''): void
388 $logResponse = $response;
390 // only log when using standard api calls (skip when using local api calls from within OpenEMR)
391 // and when api log option is set
392 if (!$GLOBALS['is_local_api'] && !self::$notRestCall && $GLOBALS['api_log_option']) {
393 if ($GLOBALS['api_log_option'] == 1) {
394 // Do not log the response and requestBody
395 $logResponse = '';
396 $requestBody = '';
398 if ($response instanceof ResponseInterface) {
399 if (self::shouldLogResponse($response)) {
400 $body = $response->getBody();
401 $logResponse = $body->getContents();
402 $body->rewind();
403 } else {
404 $logResponse = 'Content not application/json - Skip binary data';
406 } else {
407 $logResponse = (!empty($logResponse)) ? json_encode($response) : '';
410 // convert pertinent elements to json
411 $requestBody = (!empty($requestBody)) ? json_encode($requestBody) : '';
413 // prepare values and call the log function
414 $event = 'api';
415 $category = 'api';
416 $method = $_SERVER['REQUEST_METHOD'];
417 $url = $_SERVER['REQUEST_URI'];
418 $patientId = (int)($_SESSION['pid'] ?? 0);
419 $userId = (int)($_SESSION['authUserID'] ?? 0);
420 $api = [
421 'user_id' => $userId,
422 'patient_id' => $patientId,
423 'method' => $method,
424 'request' => $GLOBALS['resource'],
425 'request_url' => $url,
426 'request_body' => $requestBody,
427 'response' => $logResponse
429 if ($patientId === 0) {
430 $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
432 EventAuditLogger::instance()->recordLogItem(1, $event, ($_SESSION['authUser'] ?? ''), ($_SESSION['authProvider'] ?? ''), 'api log', $patientId, $category, 'open-emr', null, null, '', $api);
436 public static function emitResponse($response, $build = false): void
438 if (headers_sent()) {
439 throw new RuntimeException('Headers already sent.');
441 $statusLine = sprintf(
442 'HTTP/%s %s %s',
443 $response->getProtocolVersion(),
444 $response->getStatusCode(),
445 $response->getReasonPhrase()
447 header($statusLine, true);
448 foreach ($response->getHeaders() as $name => $values) {
449 $responseHeader = sprintf('%s: %s', $name, $response->getHeaderLine($name));
450 header($responseHeader, false);
452 echo $response->getBody();
456 * If the FHIR System scopes enabled or not. True if its turned on, false otherwise.
457 * @return bool
459 public static function areSystemScopesEnabled()
461 return $GLOBALS['rest_system_scopes_api'] === '1';
464 public function authenticateUserToken($tokenId, $clientId, $userId): bool
466 $ip = collectIpAddresses();
468 // check for token
469 $accessTokenRepo = new AccessTokenRepository();
470 $authTokenExpiration = $accessTokenRepo->getTokenExpiration($tokenId, $clientId, $userId);
472 if (empty($authTokenExpiration)) {
473 EventAuditLogger::instance()->newEvent('api', '', '', 0, "API failure: " . $ip['ip_string'] . ". Token not found for client[" . $clientId . "] and user " . $userId . ".");
474 return false;
477 // Ensure token not expired (note an expired token should have already been caught by oauth2, however will also check here)
478 $currentDateTime = date("Y-m-d H:i:s");
479 $expiryDateTime = date("Y-m-d H:i:s", strtotime($authTokenExpiration));
480 if ($expiryDateTime <= $currentDateTime) {
481 EventAuditLogger::instance()->newEvent('api', '', '', 0, "API failure: " . $ip['ip_string'] . ". Token expired for client[" . $clientId . "] and user " . $userId . ".");
482 return false;
485 // Token authentication passed
486 EventAuditLogger::instance()->newEvent('api', '', '', 1, "API success: " . $ip['ip_string'] . ". Token successfully used for client[" . $clientId . "] and user " . $userId . ".");
487 return true;
491 * Checks if we should log the response interface (we don't want to log binary documents or anything like that)
492 * We only log requests with a content-type of any form of json fhir+application/json or application/json
493 * @param ResponseInterface $response
494 * @return bool If the request should be logged, false otherwise
496 private static function shouldLogResponse(ResponseInterface $response)
498 if ($response->hasHeader("Content-Type")) {
499 $contentType = $response->getHeaderLine("Content-Type");
500 if ($contentType === 'application/json') {
501 return true;
505 return false;
509 * Grabs all of the context information for the request's access token and populates any context variables the
510 * request needs (such as patient binding information). Returns the populated request
511 * @param HttpRestRequest $restRequest
512 * @return HttpRestRequest
514 public function populateTokenContextForRequest(HttpRestRequest $restRequest)
517 $context = $this->getTokenContextForRequest($restRequest);
518 // note that the context here is the SMART value that is returned in the response for an AccessToken in this
519 // case it is the patient value which is the logical id (ie uuid) of the patient.
520 $patientUuid = $context['patient'] ?? null;
521 if (!empty($patientUuid)) {
522 // we only set the bound patient access if the underlying user can still access the patient
523 if ($this->checkUserHasAccessToPatient($restRequest->getRequestUserId(), $patientUuid)) {
524 $restRequest->setPatientUuidString($patientUuid);
526 } else {
527 (new SystemLogger())->error(("OpenEMR Error: api had patient launch scope but no patient was set in the "
528 . " session cache. Resources restricted with patient scopes will not return results"));
530 return $restRequest;
533 public function getTokenContextForRequest(HttpRestRequest $restRequest)
535 $accessTokenRepo = new AccessTokenRepository();
536 // note this is pretty confusing as getAccessTokenId comes from the oauth_access_id which is the token NOT
537 // the database id even though this is called accessTokenId....
538 $token = $accessTokenRepo->getTokenByToken($restRequest->getAccessTokenId());
539 $context = $token['context'] ?? "{}"; // if there is no populated context we just return an empty return
540 try {
541 return json_decode($context, true);
542 } catch (\Exception $exception) {
543 (new SystemLogger())->error("OpenEMR Error: failed to decode token context json", ['exception' => $exception->getMessage()
544 , 'tokenId' => $restRequest->getAccessTokenId()]);
546 return [];
551 * Checks whether a user has access to the patient. Returns true if the user can access the given patient, false otherwise
552 * @param $userId The id from the users table that represents the user
553 * @param $patientUuid The uuid from the patient_data table that represents the patient
554 * @return bool True if has access, false otherwise
556 private function checkUserHasAccessToPatient($userId, $patientUuid)
558 // TODO: the session should never be populated with the pid from the access token unless the user had access to
559 // it. However, if we wanted an additional check or if we anted to fire off any kind of event that does
560 // patient filtering by provider / clinic we would handle that here.
561 return true;
565 /** prevents external cloning */
566 private function __clone()
571 // Include our routes and init routes global
573 require_once(__DIR__ . "/_rest_routes.inc.php");