Merge pull request #19200 from eileenmcnaughton/act_contact
[civicrm-core.git] / CRM / Utils / REST.php
1 <?php
2 /*
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This class handles all REST client requests.
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18 class CRM_Utils_REST {
19
20 /**
21 * Number of seconds we should let a REST process idle
22 * @var int
23 */
24 public static $rest_timeout = 0;
25
26 /**
27 * Cache the actual UF Class
28 * @var string
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 *
36 * @internal param string $uf The userframework class
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 *
48 * @param string $var
49 * The string to be echoed.
50 *
51 * @return string
52 */
53 public static function ping($var = NULL) {
54 $session = CRM_Core_Session::singleton();
55 $key = $session->get('key');
56 // $session->set( 'key', $var );
57 return self::simple(['message' => "PONG: $key"]);
58 }
59
60 /**
61 * Generates values needed for error messages.
62 * @param string $message
63 *
64 * @return array
65 */
66 public static function error($message = 'Unknown Error') {
67 $values = [
68 'error_message' => $message,
69 'is_error' => 1,
70 ];
71 return $values;
72 }
73
74 /**
75 * Generates values needed for non-error responses.
76 * @param array $params
77 *
78 * @return array
79 */
80 public static function simple($params) {
81 $values = ['is_error' => 0];
82 $values += $params;
83 return $values;
84 }
85
86 /**
87 * @return string
88 */
89 public function run() {
90 $result = self::handle();
91 return self::output($result);
92 }
93
94 /**
95 * @return string
96 */
97 public function bootAndRun() {
98 $response = $this->loadCMSBootstrap();
99 if (is_array($response)) {
100 return self::output($response);
101 }
102 return $this->run();
103 }
104
105 /**
106 * @param $result
107 *
108 * @return string
109 */
110 public static function output(&$result) {
111 $requestParams = CRM_Utils_Request::exportValues();
112
113 $hier = FALSE;
114 if (is_scalar($result)) {
115 if (!$result) {
116 $result = 0;
117 }
118 $result = self::simple(['result' => $result]);
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
132 if (!empty($requestParams['json'])) {
133 if (!empty($requestParams['prettyprint'])) {
134 // Don't set content-type header for api explorer output
135 return json_encode(array_merge($result), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE);
136 return self::jsonFormated(array_merge($result));
137 }
138 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
139 return json_encode(array_merge($result));
140 }
141
142 if (isset($result['count'])) {
143 $count = ' count="' . $result['count'] . '" ';
144 }
145 else {
146 $count = "";
147 }
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) {
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 }
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
171 /**
172 * @return array|int
173 */
174 public static function handle() {
175 $requestParams = CRM_Utils_Request::exportValues();
176
177 // Get the function name being called from the q parameter in the query string
178 $q = $requestParams['q'] ?? NULL;
179 // or for the rest interface, from fnName
180 $r = $requestParams['fnName'] ?? NULL;
181 if (!empty($r)) {
182 $q = $r;
183 }
184 $entity = $requestParams['entity'] ?? NULL;
185 if (empty($entity) && !empty($q)) {
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.
193 // Does this mean it will reject it
194 if ((count($args) != 3) && ($args[1] != 'ping')) {
195 return self::error('Unknown function invocation.');
196 }
197 $store = NULL;
198
199 if ($args[1] == 'ping') {
200 return self::ping();
201 }
202 }
203 else {
204 // or the api format (entity+action)
205 $args = [];
206 $args[0] = 'civicrm';
207 $args[1] = $requestParams['entity'] ?? NULL;
208 $args[2] = $requestParams['action'] ?? NULL;
209 }
210
211 // Everyone should be required to provide the server key, so the whole
212 // interface can be disabled in more change to the configuration file.
213 // first check for civicrm site key
214 if (!CRM_Utils_System::authenticateKey(FALSE)) {
215 $docLink = CRM_Utils_System::docURL2('sysadmin/setup/jobs', TRUE);
216 $key = $requestParams['key'] ?? NULL;
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
223 // At this point we know we are not calling ping which does not require authentication.
224 // Therefore we now need a valid server key and API key.
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");
229 }
230 $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
231
232 // If we didn't find a valid user, die
233 if (empty($valid_user)) {
234 return self::error("User API key invalid");
235 }
236
237 return self::process($args, self::buildParamList());
238 }
239
240 /**
241 * @param $args
242 * @param array $params
243 *
244 * @return array|int
245 */
246 public static function process(&$args, $params) {
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
266 return call_user_func([$params['className'], $params['fnName']], $params);
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
280 if ($_SERVER['REQUEST_METHOD'] == 'GET' &&
281 strtolower(substr($args[2], 0, 3)) != 'get' &&
282 strtolower($args[2] != 'check')) {
283 // get only valid for non destructive methods
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.",
286 [
287 'IP' => $_SERVER['REMOTE_ADDR'],
288 'level' => 'security',
289 'referer' => $_SERVER['HTTP_REFERER'],
290 'reason' => 'Destructive HTTP GET',
291 ]
292 );
293 }
294
295 // trap all fatal errors
296 $errorScope = CRM_Core_TemporaryErrorScope::create([
297 'CRM_Utils_REST',
298 'fatal',
299 ]);
300 $result = civicrm_api($args[1], $args[2], $params);
301 unset($errorScope);
302
303 if ($result === FALSE) {
304 return self::error('Unknown error.');
305 }
306 return $result;
307 }
308
309 /**
310 * @return array|mixed|null
311 */
312 public static function &buildParamList() {
313 $requestParams = CRM_Utils_Request::exportValues();
314 $params = [];
315
316 $skipVars = [
317 'q' => 1,
318 'json' => 1,
319 'key' => 1,
320 'api_key' => 1,
321 'entity' => 1,
322 'action' => 1,
323 ];
324
325 if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
326 $params = json_decode($requestParams['json'], TRUE);
327 if ($params === NULL) {
328 CRM_Utils_JSON::output([
329 'is_error' => 1,
330 0 => 'error_message',
331 1 => 'Unable to decode supplied JSON.',
332 ]);
333 }
334 }
335 foreach ($requestParams as $n => $v) {
336 if (!array_key_exists($n, $skipVars)) {
337 $params[$n] = $v;
338 }
339 }
340 if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) {
341 foreach ($requestParams['return'] as $key => $v) {
342 $params['return.' . $key] = 1;
343 }
344 }
345 return $params;
346 }
347
348 /**
349 * @param $pearError
350 */
351 public static function fatal($pearError) {
352 CRM_Utils_System::setHttpHeader('Content-Type', 'text/xml');
353 $error = [];
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
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() {
372 $request = CRM_Utils_Request::retrieve('q', 'String');
373 if (FALSE !== strpos($request, '..')) {
374 die("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
375 }
376
377 $request = explode('/', $request);
378 $entity = _civicrm_api_get_camel_name($request[2]);
379 $tplfile = _civicrm_api_get_camel_name($request[3]);
380
381 $tpl = 'CRM/' . $entity . '/Page/Inline/' . $tplfile . '.tpl';
382 $smarty = CRM_Core_Smarty::singleton();
383 CRM_Utils_System::setTitle("$entity::$tplfile inline $tpl");
384 if (!$smarty->template_exists($tpl)) {
385 CRM_Utils_System::setHttpHeader("Status", "404 Not Found");
386 die("Can't find the requested template file templates/$tpl");
387 }
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']);
392 }
393 $pos = strpos(implode(array_keys($_GET)), '<');
394
395 if ($pos !== FALSE) {
396 die("SECURITY FATAL: one of the param names contains &lt;");
397 }
398 $param = array_map('htmlentities', $_GET);
399 unset($param['q']);
400 $smarty->assign_by_ref("request", $param);
401
402 if (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
403 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
404 ) {
405
406 $smarty->assign('tplFile', $tpl);
407 $config = CRM_Core_Config::singleton();
408 $content = $smarty->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl');
409
410 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) {
411 CRM_Utils_System::addHTMLHead($region->render(''));
412 }
413 CRM_Utils_System::appendTPLFile($tpl, $content);
414
415 return CRM_Utils_System::theme($content);
416
417 }
418 else {
419 $content = "<!-- .tpl file embedded: $tpl -->\n";
420 CRM_Utils_System::appendTPLFile($tpl, $content);
421 echo $content . $smarty->fetch($tpl);
422 CRM_Utils_System::civiExit();
423 }
424 }
425
426 /**
427 * This is a wrapper so you can call an api via json (it returns json too)
428 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}}
429 * to take all the emails from individuals.
430 * Works for POST & GET (POST recommended).
431 */
432 public static function ajaxJson() {
433 $requestParams = CRM_Utils_Request::exportValues();
434
435 require_once 'api/v3/utils.php';
436 $config = CRM_Core_Config::singleton();
437 if (!$config->debug && (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
438 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
439 )
440 ) {
441 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
442 [
443 'IP' => $_SERVER['REMOTE_ADDR'],
444 'level' => 'security',
445 'referer' => $_SERVER['HTTP_REFERER'],
446 'reason' => 'CSRF suspected',
447 ]
448 );
449 CRM_Utils_JSON::output($error);
450 }
451 if (empty($requestParams['entity'])) {
452 CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity param'));
453 }
454 if (empty($requestParams['entity'])) {
455 CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity entity'));
456 }
457 if (!empty($requestParams['json'])) {
458 $params = json_decode($requestParams['json'], TRUE);
459 }
460 $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams));
461 $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams));
462 if (!is_array($params)) {
463 CRM_Utils_JSON::output([
464 'is_error' => 1,
465 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}',
466 ]);
467 }
468
469 $params['check_permissions'] = TRUE;
470 $params['version'] = 3;
471 // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
472 $_GET['json'] = $requestParams['json'] = 1;
473 if (!$params['sequential']) {
474 $params['sequential'] = 1;
475 }
476
477 // trap all fatal errors
478 $errorScope = CRM_Core_TemporaryErrorScope::create([
479 'CRM_Utils_REST',
480 'fatal',
481 ]);
482 $result = civicrm_api($entity, $action, $params);
483 unset($errorScope);
484
485 echo self::output($result);
486
487 CRM_Utils_System::civiExit();
488 }
489
490 /**
491 * Run ajax request.
492 *
493 * @return array
494 */
495 public static function ajax() {
496 $requestParams = CRM_Utils_Request::exportValues();
497
498 // this is driven by the menu system, so we can use permissioning to
499 // restrict calls to this etc
500 // the request has to be sent by an ajax call. First line of protection against csrf
501 $config = CRM_Core_Config::singleton();
502 if (!$config->debug &&
503 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
504 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
505 )
506 ) {
507 require_once 'api/v3/utils.php';
508 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
509 [
510 'IP' => $_SERVER['REMOTE_ADDR'],
511 'level' => 'security',
512 'referer' => $_SERVER['HTTP_REFERER'],
513 'reason' => 'CSRF suspected',
514 ]
515 );
516 CRM_Utils_JSON::output($error);
517 }
518
519 $q = $requestParams['fnName'] ?? NULL;
520 if (!$q) {
521 $entity = $requestParams['entity'] ?? NULL;
522 $action = $requestParams['action'] ?? NULL;
523 if (!$entity || !$action) {
524 $err = [
525 'error_message' => 'missing mandatory params "entity=" or "action="',
526 'is_error' => 1,
527 ];
528 echo self::output($err);
529 CRM_Utils_System::civiExit();
530 }
531 $args = ['civicrm', $entity, $action];
532 }
533 else {
534 $args = explode('/', $q);
535 }
536
537 // get the class name, since all ajax functions pass className
538 $className = $requestParams['className'] ?? NULL;
539
540 // If the function isn't in the civicrm namespace, reject the request.
541 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
542 return self::error('Unknown function invocation.');
543 }
544
545 // Support for multiple api calls
546 if (isset($entity) && $entity === 'api3') {
547 $result = self::processMultiple();
548 }
549 else {
550 $result = self::process($args, self::buildParamList());
551 }
552
553 echo self::output($result);
554
555 CRM_Utils_System::civiExit();
556 }
557
558 /**
559 * Callback for multiple ajax api calls from CRM.api3()
560 * @return array
561 */
562 public static function processMultiple() {
563 $output = [];
564 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
565 $args = [
566 'civicrm',
567 $call[0],
568 $call[1],
569 ];
570 $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, []));
571 }
572 return $output;
573 }
574
575 /**
576 * @return array|NULL
577 * NULL if execution should proceed; array if the response is already known
578 */
579 public function loadCMSBootstrap() {
580 $requestParams = CRM_Utils_Request::exportValues();
581 $q = $requestParams['q'] ?? NULL;
582 $args = explode('/', $q);
583
584 // Proceed with bootstrap for "?entity=X&action=Y"
585 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
586 if (!empty($q)) {
587 if (count($args) == 2 && $args[1] == 'ping') {
588 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
589 // this is pretty wonky but maybe there's some reason I can't see
590 return NULL;
591 }
592 if (count($args) != 3) {
593 return self::error('ERROR: Malformed REST path');
594 }
595 if ($args[0] != 'civicrm') {
596 return self::error('ERROR: Malformed REST path');
597 }
598 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
599 }
600
601 if (!CRM_Utils_System::authenticateKey(FALSE)) {
602 // FIXME: At time of writing, this doesn't actually do anything because
603 // authenticateKey abends, but that's a bad behavior which sends a
604 // malformed response.
605 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
606 return self::error('Failed to authenticate key');
607 }
608
609 $uid = NULL;
610 if (!$uid) {
611 $store = NULL;
612 $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
613 if (empty($api_key)) {
614 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
615 return self::error("FATAL: mandatory param 'api_key' (user key) missing");
616 }
617 $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
618 if ($contact_id) {
619 $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
620 }
621 }
622
623 if ($uid && $contact_id) {
624 CRM_Utils_System::loadBootStrap(['uid' => $uid], TRUE, FALSE);
625 $session = CRM_Core_Session::singleton();
626 $session->set('ufID', $uid);
627 $session->set('userID', $contact_id);
628 CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
629 [1 => [$contact_id, 'Integer']]
630 );
631 return NULL;
632 }
633 else {
634 CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
635 return self::error('ERROR: No CMS user associated with given api-key');
636 }
637 }
638
639 }