Merge pull request #23121 from eileenmcnaughton/imp
[civicrm-core.git] / CRM / Utils / REST.php
CommitLineData
6a488035
TO
1<?php
2/*
bc77d7c0
TO
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
6a488035
TO
10 */
11
12/**
13 * This class handles all REST client requests.
14 *
15 * @package CRM
ca5cec67 16 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
17 */
18class CRM_Utils_REST {
19
20 /**
21 * Number of seconds we should let a REST process idle
6714d8d2 22 * @var int
6a488035 23 */
6714d8d2 24 public static $rest_timeout = 0;
6a488035
TO
25
26 /**
27 * Cache the actual UF Class
6714d8d2 28 * @var string
6a488035
TO
29 */
30 public $ufClass;
31
32 /**
33 * Class constructor. This caches the real user framework class locally,
34 * so we can use it for authentication and validation.
35 *
f4aaa82a 36 * @internal param string $uf The userframework class
6a488035
TO
37 */
38 public function __construct() {
39 // any external program which call Rest Server is responsible for
40 // creating and attaching the session
41 $args = func_get_args();
42 $this->ufClass = array_shift($args);
43 }
44
45 /**
46 * Simple ping function to test for liveness.
47 *
77855840
TO
48 * @param string $var
49 * The string to be echoed.
6a488035 50 *
e0f5b841 51 * @return array
6a488035 52 */
7f2d6a61 53 public static function ping($var = NULL) {
6a488035
TO
54 $session = CRM_Core_Session::singleton();
55 $key = $session->get('key');
50bfb460 56 // $session->set( 'key', $var );
b3325339 57 return self::simple(['message' => "PONG: $key"]);
6a488035
TO
58 }
59
5bc392e6 60 /**
fe482240 61 * Generates values needed for error messages.
5bc392e6
EM
62 * @param string $message
63 *
64 * @return array
65 */
00be9182 66 public static function error($message = 'Unknown Error') {
b3325339 67 $values = [
6a488035
TO
68 'error_message' => $message,
69 'is_error' => 1,
b3325339 70 ];
6a488035
TO
71 return $values;
72 }
73
5bc392e6 74 /**
4f1f1f2a 75 * Generates values needed for non-error responses.
c490a46a 76 * @param array $params
5bc392e6
EM
77 *
78 * @return array
79 */
00be9182 80 public static function simple($params) {
b3325339 81 $values = ['is_error' => 0];
6a488035
TO
82 $values += $params;
83 return $values;
84 }
85
5bc392e6
EM
86 /**
87 * @return string
88 */
00be9182 89 public function run() {
6a488035
TO
90 $result = self::handle();
91 return self::output($result);
92 }
93
5bc392e6
EM
94 /**
95 * @return string
96 */
00be9182 97 public function bootAndRun() {
7f2d6a61
TO
98 $response = $this->loadCMSBootstrap();
99 if (is_array($response)) {
100 return self::output($response);
101 }
102 return $this->run();
103 }
104
5bc392e6
EM
105 /**
106 * @param $result
107 *
108 * @return string
109 */
00be9182 110 public static function output(&$result) {
ba56a28f
TO
111 $requestParams = CRM_Utils_Request::exportValues();
112
6a488035
TO
113 $hier = FALSE;
114 if (is_scalar($result)) {
115 if (!$result) {
116 $result = 0;
117 }
b3325339 118 $result = self::simple(['result' => $result]);
6a488035
TO
119 }
120 elseif (is_array($result)) {
121 if (CRM_Utils_Array::isHierarchical($result)) {
122 $hier = TRUE;
123 }
124 elseif (!array_key_exists('is_error', $result)) {
125 $result['is_error'] = 0;
126 }
127 }
128 else {
129 $result = self::error('Could not interpret return values from function.');
130 }
131
3eec106c 132 if (!empty($requestParams['json'])) {
3eec106c 133 if (!empty($requestParams['prettyprint'])) {
b308e50d 134 // Don't set content-type header for api explorer output
2d4a140a 135 return json_encode(array_merge($result), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE);
108bcf37 136 return self::jsonFormated(array_merge($result));
6a488035 137 }
b308e50d 138 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
108bcf37 139 return json_encode(array_merge($result));
6a488035
TO
140 }
141
6a488035 142 if (isset($result['count'])) {
6a488035 143 $count = ' count="' . $result['count'] . '" ';
6a488035 144 }
a3e55d9c
TO
145 else {
146 $count = "";
e7292422 147 }
6a488035
TO
148 $xml = "<?xml version=\"1.0\"?>
149 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
150 ";
151 // check if this is a single element result (contact_get etc)
152 // or multi element
153 if ($hier) {
59a4addf
AN
154 foreach ($result['values'] as $k => $v) {
155 if (is_array($v)) {
156 $xml .= "<Result>\n" . CRM_Utils_Array::xml($v) . "</Result>\n";
157 }
158 elseif (!is_object($v)) {
159 $xml .= "<Result>\n<id>{$k}</id><value>{$v}</value></Result>\n";
160 }
6a488035
TO
161 }
162 }
163 else {
164 $xml .= "<Result>\n" . CRM_Utils_Array::xml($result) . "</Result>\n";
165 }
166
167 $xml .= "</ResultSet>\n";
168 return $xml;
169 }
170
5bc392e6
EM
171 /**
172 * @return array|int
173 */
00be9182 174 public static function handle() {
ba56a28f
TO
175 $requestParams = CRM_Utils_Request::exportValues();
176
6a488035 177 // Get the function name being called from the q parameter in the query string
9c1bc317 178 $q = $requestParams['q'] ?? NULL;
6a488035 179 // or for the rest interface, from fnName
9c1bc317 180 $r = $requestParams['fnName'] ?? NULL;
6a488035
TO
181 if (!empty($r)) {
182 $q = $r;
183 }
9c1bc317 184 $entity = $requestParams['entity'] ?? NULL;
481a74f4 185 if (empty($entity) && !empty($q)) {
6a488035
TO
186 $args = explode('/', $q);
187 // If the function isn't in the civicrm namespace, reject the request.
188 if ($args[0] != 'civicrm') {
189 return self::error('Unknown function invocation.');
190 }
191
192 // If the query string is malformed, reject the request.
7f2d6a61
TO
193 // Does this mean it will reject it
194 if ((count($args) != 3) && ($args[1] != 'ping')) {
6a488035
TO
195 return self::error('Unknown function invocation.');
196 }
197 $store = NULL;
f813f78e 198
7f2d6a61 199 if ($args[1] == 'ping') {
6a488035
TO
200 return self::ping();
201 }
0db6c3e1
TO
202 }
203 else {
650ff635 204 // or the api format (entity+action)
b3325339 205 $args = [];
7f2d6a61 206 $args[0] = 'civicrm';
9c1bc317
CW
207 $args[1] = $requestParams['entity'] ?? NULL;
208 $args[2] = $requestParams['action'] ?? NULL;
6a488035 209 }
f813f78e 210
6a488035 211 // Everyone should be required to provide the server key, so the whole
50bfb460 212 // interface can be disabled in more change to the configuration file.
6a488035
TO
213 // first check for civicrm site key
214 if (!CRM_Utils_System::authenticateKey(FALSE)) {
23af1818 215 $docLink = CRM_Utils_System::docURL2('sysadmin/setup/jobs', TRUE);
9c1bc317 216 $key = $requestParams['key'] ?? NULL;
6a488035
TO
217 if (empty($key)) {
218 return self::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
219 }
220 return self::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
221 }
222
7f2d6a61 223 // At this point we know we are not calling ping which does not require authentication.
50bfb460 224 // Therefore we now need a valid server key and API key.
7f2d6a61
TO
225 // Check and see if a valid secret API key is provided.
226 $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
227 if (!$api_key || strtolower($api_key) == 'null') {
228 return self::error("FATAL: mandatory param 'api_key' (user key) missing");
6a488035 229 }
7f2d6a61 230 $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
6a488035 231
7f2d6a61 232 // If we didn't find a valid user, die
6a488035 233 if (empty($valid_user)) {
7f2d6a61 234 return self::error("User API key invalid");
6a488035
TO
235 }
236
a323a20f 237 return self::process($args, self::buildParamList());
6a488035
TO
238 }
239
5bc392e6
EM
240 /**
241 * @param $args
c490a46a 242 * @param array $params
5bc392e6
EM
243 *
244 * @return array|int
245 */
00be9182 246 public static function process(&$args, $params) {
6a488035
TO
247 $params['check_permissions'] = TRUE;
248 $fnName = $apiFile = NULL;
249 // clean up all function / class names. they should be alphanumeric and _ only
250 for ($i = 1; $i <= 3; $i++) {
251 if (!empty($args[$i])) {
252 $args[$i] = CRM_Utils_String::munge($args[$i]);
253 }
254 }
255
256 // incase of ajax functions className is passed in url
257 if (isset($params['className'])) {
258 $params['className'] = CRM_Utils_String::munge($params['className']);
259
260 // functions that are defined only in AJAX.php can be called via
261 // rest interface
262 if (!CRM_Core_Page_AJAX::checkAuthz('method', $params['className'], $params['fnName'])) {
263 return self::error('Unknown function invocation.');
264 }
265
b3325339 266 return call_user_func([$params['className'], $params['fnName']], $params);
6a488035
TO
267 }
268
269 if (!array_key_exists('version', $params)) {
270 $params['version'] = 3;
271 }
272
273 if ($params['version'] == 2) {
274 $result['is_error'] = 1;
275 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
276 $result['deprecated'] = "Please upgrade to API v3";
277 return $result;
278 }
279
92c11e8c 280 if ($_SERVER['REQUEST_METHOD'] == 'GET' &&
b3325339 281 strtolower(substr($args[2], 0, 3)) != 'get' &&
282 strtolower($args[2] != 'check')) {
f9e16e9a 283 // get only valid for non destructive methods
6a488035
TO
284 require_once 'api/v3/utils.php';
285 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
b3325339 286 [
6a488035
TO
287 'IP' => $_SERVER['REMOTE_ADDR'],
288 'level' => 'security',
289 'referer' => $_SERVER['HTTP_REFERER'],
290 'reason' => 'Destructive HTTP GET',
b3325339 291 ]
6a488035
TO
292 );
293 }
294
295 // trap all fatal errors
b3325339 296 $errorScope = CRM_Core_TemporaryErrorScope::create([
297 'CRM_Utils_REST',
298 'fatal',
299 ]);
6a488035 300 $result = civicrm_api($args[1], $args[2], $params);
ca32aecc 301 unset($errorScope);
6a488035
TO
302
303 if ($result === FALSE) {
304 return self::error('Unknown error.');
305 }
306 return $result;
307 }
308
5bc392e6
EM
309 /**
310 * @return array|mixed|null
311 */
00be9182 312 public static function &buildParamList() {
ba56a28f 313 $requestParams = CRM_Utils_Request::exportValues();
b3325339 314 $params = [];
6a488035 315
b3325339 316 $skipVars = [
6a488035
TO
317 'q' => 1,
318 'json' => 1,
319 'key' => 1,
320 'api_key' => 1,
321 'entity' => 1,
322 'action' => 1,
b3325339 323 ];
6a488035 324
353ffa53 325 if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
ba56a28f 326 $params = json_decode($requestParams['json'], TRUE);
22e263ad 327 if ($params === NULL) {
b3325339 328 CRM_Utils_JSON::output([
329 'is_error' => 1,
330 0 => 'error_message',
331 1 => 'Unable to decode supplied JSON.',
332 ]);
6a488035
TO
333 }
334 }
ba56a28f 335 foreach ($requestParams as $n => $v) {
6a488035
TO
336 if (!array_key_exists($n, $skipVars)) {
337 $params[$n] = $v;
338 }
339 }
ba56a28f 340 if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) {
a3e55d9c
TO
341 foreach ($requestParams['return'] as $key => $v) {
342 $params['return.' . $key] = 1;
e7292422 343 }
6a488035
TO
344 }
345 return $params;
346 }
347
5bc392e6
EM
348 /**
349 * @param $pearError
350 */
00be9182 351 public static function fatal($pearError) {
d42a224c 352 CRM_Utils_System::setHttpHeader('Content-Type', 'text/xml');
b3325339 353 $error = [];
6a488035
TO
354 $error['code'] = $pearError->getCode();
355 $error['error_message'] = $pearError->getMessage();
356 $error['mode'] = $pearError->getMode();
357 $error['debug_info'] = $pearError->getDebugInfo();
358 $error['type'] = $pearError->getType();
359 $error['user_info'] = $pearError->getUserInfo();
360 $error['to_string'] = $pearError->toString();
361 $error['is_error'] = 1;
362
363 echo self::output($error);
364
365 CRM_Utils_System::civiExit();
366 }
367
d5cc0fc2 368 /**
369 * used to load a template "inline", eg. for ajax, without having to build a menu for each template
370 */
371 public static function loadTemplate() {
481a74f4 372 $request = CRM_Utils_Request::retrieve('q', 'String');
e7292422 373 if (FALSE !== strpos($request, '..')) {
b3325339 374 die("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
6a488035
TO
375 }
376
d3e86119 377 $request = explode('/', $request);
6a488035 378 $entity = _civicrm_api_get_camel_name($request[2]);
e7292422 379 $tplfile = _civicrm_api_get_camel_name($request[3]);
6a488035 380
92fcb95f 381 $tpl = 'CRM/' . $entity . '/Page/Inline/' . $tplfile . '.tpl';
481a74f4
TO
382 $smarty = CRM_Core_Smarty::singleton();
383 CRM_Utils_System::setTitle("$entity::$tplfile inline $tpl");
384 if (!$smarty->template_exists($tpl)) {
d42a224c 385 CRM_Utils_System::setHttpHeader("Status", "404 Not Found");
b3325339 386 die("Can't find the requested template file templates/$tpl");
6a488035 387 }
6714d8d2
SL
388 // special treatmenent, because it's often used
389 if (array_key_exists('id', $_GET)) {
390 // an id is always positive
391 $smarty->assign('id', (int) $_GET['id']);
6a488035 392 }
e7292422 393 $pos = strpos(implode(array_keys($_GET)), '<');
6a488035 394
e7292422 395 if ($pos !== FALSE) {
b3325339 396 die("SECURITY FATAL: one of the param names contains &lt;");
6a488035 397 }
481a74f4 398 $param = array_map('htmlentities', $_GET);
6a488035
TO
399 unset($param['q']);
400 $smarty->assign_by_ref("request", $param);
401
12739440 402 if (!self::isWebServiceRequest()) {
6a488035 403
481a74f4 404 $smarty->assign('tplFile', $tpl);
e7292422 405 $config = CRM_Core_Config::singleton();
353ffa53 406 $content = $smarty->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl');
6a488035 407
e7292422
TO
408 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) {
409 CRM_Utils_System::addHTMLHead($region->render(''));
410 }
481a74f4 411 CRM_Utils_System::appendTPLFile($tpl, $content);
6a488035 412
e7292422 413 return CRM_Utils_System::theme($content);
6a488035 414
0db6c3e1
TO
415 }
416 else {
b44e3f84 417 $content = "<!-- .tpl file embedded: $tpl -->\n";
481a74f4 418 CRM_Utils_System::appendTPLFile($tpl, $content);
e7292422 419 echo $content . $smarty->fetch($tpl);
481a74f4 420 CRM_Utils_System::civiExit();
6a488035
TO
421 }
422 }
423
d5cc0fc2 424 /**
425 * This is a wrapper so you can call an api via json (it returns json too)
50bfb460
SB
426 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}}
427 * to take all the emails from individuals.
428 * Works for POST & GET (POST recommended).
d5cc0fc2 429 */
00be9182 430 public static function ajaxJson() {
ba56a28f
TO
431 $requestParams = CRM_Utils_Request::exportValues();
432
6a488035 433 require_once 'api/v3/utils.php';
650ff635 434 $config = CRM_Core_Config::singleton();
12739440 435 if (!$config->debug && !self::isWebServiceRequest()) {
e4176358 436 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
b3325339 437 [
6a488035
TO
438 'IP' => $_SERVER['REMOTE_ADDR'],
439 'level' => 'security',
440 'referer' => $_SERVER['HTTP_REFERER'],
441 'reason' => 'CSRF suspected',
b3325339 442 ]
6a488035 443 );
ecdef330 444 CRM_Utils_JSON::output($error);
6a488035 445 }
ba56a28f 446 if (empty($requestParams['entity'])) {
ecdef330 447 CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity param'));
6a488035 448 }
ba56a28f 449 if (empty($requestParams['entity'])) {
ecdef330 450 CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity entity'));
6a488035 451 }
ba56a28f
TO
452 if (!empty($requestParams['json'])) {
453 $params = json_decode($requestParams['json'], TRUE);
6a488035 454 }
ba56a28f
TO
455 $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams));
456 $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams));
6a488035 457 if (!is_array($params)) {
b3325339 458 CRM_Utils_JSON::output([
459 'is_error' => 1,
460 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}',
461 ]);
6a488035
TO
462 }
463
464 $params['check_permissions'] = TRUE;
465 $params['version'] = 3;
6714d8d2
SL
466 // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
467 $_GET['json'] = $requestParams['json'] = 1;
6a488035
TO
468 if (!$params['sequential']) {
469 $params['sequential'] = 1;
470 }
ca32aecc 471
6a488035 472 // trap all fatal errors
b3325339 473 $errorScope = CRM_Core_TemporaryErrorScope::create([
474 'CRM_Utils_REST',
475 'fatal',
476 ]);
6a488035 477 $result = civicrm_api($entity, $action, $params);
ca32aecc 478 unset($errorScope);
6a488035
TO
479
480 echo self::output($result);
481
482 CRM_Utils_System::civiExit();
483 }
484
b896fa44
EM
485 /**
486 * Run ajax request.
487 *
488 * @return array
489 */
00be9182 490 public static function ajax() {
ba56a28f
TO
491 $requestParams = CRM_Utils_Request::exportValues();
492
6a488035
TO
493 // this is driven by the menu system, so we can use permissioning to
494 // restrict calls to this etc
495 // the request has to be sent by an ajax call. First line of protection against csrf
496 $config = CRM_Core_Config::singleton();
12739440 497 if (!$config->debug && !self::isWebServiceRequest()) {
6a488035 498 require_once 'api/v3/utils.php';
a323a20f 499 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
b3325339 500 [
6a488035
TO
501 'IP' => $_SERVER['REMOTE_ADDR'],
502 'level' => 'security',
503 'referer' => $_SERVER['HTTP_REFERER'],
504 'reason' => 'CSRF suspected',
b3325339 505 ]
6a488035 506 );
ecdef330 507 CRM_Utils_JSON::output($error);
6a488035
TO
508 }
509
9c1bc317 510 $q = $requestParams['fnName'] ?? NULL;
6a488035 511 if (!$q) {
9c1bc317
CW
512 $entity = $requestParams['entity'] ?? NULL;
513 $action = $requestParams['action'] ?? NULL;
6a488035 514 if (!$entity || !$action) {
b3325339 515 $err = [
516 'error_message' => 'missing mandatory params "entity=" or "action="',
517 'is_error' => 1,
518 ];
6a488035
TO
519 echo self::output($err);
520 CRM_Utils_System::civiExit();
521 }
b3325339 522 $args = ['civicrm', $entity, $action];
6a488035
TO
523 }
524 else {
525 $args = explode('/', $q);
526 }
527
528 // get the class name, since all ajax functions pass className
9c1bc317 529 $className = $requestParams['className'] ?? NULL;
6a488035
TO
530
531 // If the function isn't in the civicrm namespace, reject the request.
532 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
533 return self::error('Unknown function invocation.');
534 }
535
a323a20f
CW
536 // Support for multiple api calls
537 if (isset($entity) && $entity === 'api3') {
538 $result = self::processMultiple();
539 }
540 else {
541 $result = self::process($args, self::buildParamList());
542 }
6a488035
TO
543
544 echo self::output($result);
545
546 CRM_Utils_System::civiExit();
547 }
548
a323a20f
CW
549 /**
550 * Callback for multiple ajax api calls from CRM.api3()
551 * @return array
552 */
00be9182 553 public static function processMultiple() {
b3325339 554 $output = [];
a323a20f 555 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
b3325339 556 $args = [
a323a20f
CW
557 'civicrm',
558 $call[0],
559 $call[1],
b3325339 560 ];
561 $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, []));
a323a20f
CW
562 }
563 return $output;
564 }
565
7f2d6a61 566 /**
72b3a70c
CW
567 * @return array|NULL
568 * NULL if execution should proceed; array if the response is already known
7f2d6a61 569 */
00be9182 570 public function loadCMSBootstrap() {
ba56a28f 571 $requestParams = CRM_Utils_Request::exportValues();
9c1bc317 572 $q = $requestParams['q'] ?? NULL;
6a488035
TO
573 $args = explode('/', $q);
574
7f2d6a61
TO
575 // Proceed with bootstrap for "?entity=X&action=Y"
576 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
577 if (!empty($q)) {
578 if (count($args) == 2 && $args[1] == 'ping') {
b3325339 579 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
6714d8d2
SL
580 // this is pretty wonky but maybe there's some reason I can't see
581 return NULL;
7f2d6a61
TO
582 }
583 if (count($args) != 3) {
584 return self::error('ERROR: Malformed REST path');
585 }
586 if ($args[0] != 'civicrm') {
587 return self::error('ERROR: Malformed REST path');
588 }
589 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
6a488035
TO
590 }
591
592 if (!CRM_Utils_System::authenticateKey(FALSE)) {
7f2d6a61
TO
593 // FIXME: At time of writing, this doesn't actually do anything because
594 // authenticateKey abends, but that's a bad behavior which sends a
595 // malformed response.
b3325339 596 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
7f2d6a61 597 return self::error('Failed to authenticate key');
6a488035
TO
598 }
599
600 $uid = NULL;
6a488035 601 if (!$uid) {
353ffa53
TO
602 $store = NULL;
603 $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
7f2d6a61 604 if (empty($api_key)) {
b3325339 605 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
7f2d6a61
TO
606 return self::error("FATAL: mandatory param 'api_key' (user key) missing");
607 }
6a488035
TO
608 $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
609 if ($contact_id) {
610 $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
611 }
612 }
613
f320e5cd 614 if ($uid && $contact_id) {
b3325339 615 CRM_Utils_System::loadBootStrap(['uid' => $uid], TRUE, FALSE);
f320e5cd
DK
616 $session = CRM_Core_Session::singleton();
617 $session->set('ufID', $uid);
618 $session->set('userID', $contact_id);
35f52ba9 619 CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
b3325339 620 [1 => [$contact_id, 'Integer']]
35f52ba9 621 );
7f2d6a61
TO
622 return NULL;
623 }
624 else {
b3325339 625 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
7f2d6a61 626 return self::error('ERROR: No CMS user associated with given api-key');
6a488035
TO
627 }
628 }
96025800 629
12739440
TO
630 /**
631 * Does this request appear to be a web-service request?
632 *
690959ee
TO
633 * It is important to distinguish regular browser-page-loads from web-service-requests. Regular
634 * page-loads can be CSRF vectors, and we don't web-services to run via CSRF.
bd42f5c2 635 *
12739440 636 * @return bool
bd42f5c2
TO
637 * TRUE if the current request appears to either XMLHttpRequest or non-browser-based.
638 * Indicated by either (a) custom headers like `X-Request-With`/`X-Civi-Auth`
639 * or (b) strong-secret-params that could theoretically appear in URL bar but which
640 * cannot be meaningfully forged for CSRF purposes (like `?api_key=SECRET` or `?_authx=SECRET`).
641 * FALSE if the current request looks like a standard browser request. This request may be generated by
642 * <A HREF>, <IFRAME>, <IMG>, `Location:`, or similar CSRF vector.
12739440 643 */
690959ee 644 public static function isWebServiceRequest(): bool {
bd42f5c2
TO
645 if (($_SERVER['HTTP_X_REQUESTED_WITH'] ?? NULL) === 'XMLHttpRequest') {
646 return TRUE;
647 }
648
690959ee 649 // If authx is enabled, and if the user gives a credential, it will store metadata.
bd42f5c2 650 $authx = \CRM_Core_Session::singleton()->get('authx');
690959ee
TO
651 $allowFlows = [
652 // Some flows are resistant to CSRF. Allow these:
653
654 // <legacyrest> Current request has valid `?api_key=SECRET&key=SECRET` ==> Strong-secret params
655 'legacyrest',
656
657 // <param> Current request has valid `?_authx=SECRET` ==> Strong-secret param
658 'param',
659
660 // <xheader> Current request has valid `X-Civi-Auth:` ==> Custom header AND strong-secret param
661 'xheader',
662
663 // Other flows are not resistant to CSRF on their own (need combo w/`X-Requested-With:`).
664 // Ignore these:
665 // <login> Relies on a session `Cookie:` (which browsers re-send automatically).
666 // <auto> First request might be resistant, but all others use session `Cookie:`.
667 // <header> Browsers often retain list of credentials and re-send automatically.
668 ];
669
bd42f5c2
TO
670 if (!empty($authx) && in_array($authx['flow'], $allowFlows)) {
671 return TRUE;
672 }
673
674 return FALSE;
12739440
TO
675 }
676
6a488035 677}