3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This class handles all REST client requests.
32 * @copyright CiviCRM LLC (c) 2004-2019
34 class CRM_Utils_REST
{
37 * Number of seconds we should let a REST process idle
39 static $rest_timeout = 0;
42 * Cache the actual UF Class
47 * Class constructor. This caches the real user framework class locally,
48 * so we can use it for authentication and validation.
50 * @internal param string $uf The userframework class
52 public function __construct() {
53 // any external program which call Rest Server is responsible for
54 // creating and attaching the session
55 $args = func_get_args();
56 $this->ufClass
= array_shift($args);
60 * Simple ping function to test for liveness.
63 * The string to be echoed.
67 public static function ping($var = NULL) {
68 $session = CRM_Core_Session
::singleton();
69 $key = $session->get('key');
70 // $session->set( 'key', $var );
71 return self
::simple(['message' => "PONG: $key"]);
75 * Generates values needed for error messages.
76 * @param string $message
80 public static function error($message = 'Unknown Error') {
82 'error_message' => $message,
89 * Generates values needed for non-error responses.
90 * @param array $params
94 public static function simple($params) {
95 $values = ['is_error' => 0];
103 public function run() {
104 $result = self
::handle();
105 return self
::output($result);
111 public function bootAndRun() {
112 $response = $this->loadCMSBootstrap();
113 if (is_array($response)) {
114 return self
::output($response);
124 public static function output(&$result) {
125 $requestParams = CRM_Utils_Request
::exportValues();
128 if (is_scalar($result)) {
132 $result = self
::simple(['result' => $result]);
134 elseif (is_array($result)) {
135 if (CRM_Utils_Array
::isHierarchical($result)) {
138 elseif (!array_key_exists('is_error', $result)) {
139 $result['is_error'] = 0;
143 $result = self
::error('Could not interpret return values from function.');
146 if (!empty($requestParams['json'])) {
147 if (!empty($requestParams['prettyprint'])) {
148 // Don't set content-type header for api explorer output
149 return json_encode(array_merge($result), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE
);
150 return self
::jsonFormated(array_merge($result));
152 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/json');
153 return json_encode(array_merge($result));
156 if (isset($result['count'])) {
157 $count = ' count="' . $result['count'] . '" ';
162 $xml = "<?xml version=\"1.0\"?>
163 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
165 // check if this is a single element result (contact_get etc)
168 foreach ($result['values'] as $k => $v) {
170 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($v) . "</Result>\n";
172 elseif (!is_object($v)) {
173 $xml .= "<Result>\n<id>{$k}</id><value>{$v}</value></Result>\n";
178 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($result) . "</Result>\n";
181 $xml .= "</ResultSet>\n";
188 public static function handle() {
189 $requestParams = CRM_Utils_Request
::exportValues();
191 // Get the function name being called from the q parameter in the query string
192 $q = CRM_Utils_Array
::value('q', $requestParams);
193 // or for the rest interface, from fnName
194 $r = CRM_Utils_Array
::value('fnName', $requestParams);
198 $entity = CRM_Utils_Array
::value('entity', $requestParams);
199 if (empty($entity) && !empty($q)) {
200 $args = explode('/', $q);
201 // If the function isn't in the civicrm namespace, reject the request.
202 if ($args[0] != 'civicrm') {
203 return self
::error('Unknown function invocation.');
206 // If the query string is malformed, reject the request.
207 // Does this mean it will reject it
208 if ((count($args) != 3) && ($args[1] != 'ping')) {
209 return self
::error('Unknown function invocation.');
213 if ($args[1] == 'ping') {
218 // or the api format (entity+action)
220 $args[0] = 'civicrm';
221 $args[1] = CRM_Utils_Array
::value('entity', $requestParams);
222 $args[2] = CRM_Utils_Array
::value('action', $requestParams);
225 // Everyone should be required to provide the server key, so the whole
226 // interface can be disabled in more change to the configuration file.
227 // first check for civicrm site key
228 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
229 $docLink = CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
230 $key = CRM_Utils_Array
::value('key', $requestParams);
232 return self
::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
234 return self
::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
237 // At this point we know we are not calling ping which does not require authentication.
238 // Therefore we now need a valid server key and API key.
239 // Check and see if a valid secret API key is provided.
240 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
241 if (!$api_key ||
strtolower($api_key) == 'null') {
242 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
244 $valid_user = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
246 // If we didn't find a valid user, die
247 if (empty($valid_user)) {
248 return self
::error("User API key invalid");
251 return self
::process($args, self
::buildParamList());
256 * @param array $params
260 public static function process(&$args, $params) {
261 $params['check_permissions'] = TRUE;
262 $fnName = $apiFile = NULL;
263 // clean up all function / class names. they should be alphanumeric and _ only
264 for ($i = 1; $i <= 3; $i++
) {
265 if (!empty($args[$i])) {
266 $args[$i] = CRM_Utils_String
::munge($args[$i]);
270 // incase of ajax functions className is passed in url
271 if (isset($params['className'])) {
272 $params['className'] = CRM_Utils_String
::munge($params['className']);
274 // functions that are defined only in AJAX.php can be called via
276 if (!CRM_Core_Page_AJAX
::checkAuthz('method', $params['className'], $params['fnName'])) {
277 return self
::error('Unknown function invocation.');
280 return call_user_func([$params['className'], $params['fnName']], $params);
283 if (!array_key_exists('version', $params)) {
284 $params['version'] = 3;
287 if ($params['version'] == 2) {
288 $result['is_error'] = 1;
289 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
290 $result['deprecated'] = "Please upgrade to API v3";
294 if ($_SERVER['REQUEST_METHOD'] == 'GET' &&
295 strtolower(substr($args[2], 0, 3)) != 'get' &&
296 strtolower($args[2] != 'check')) {
297 // get only valid for non destructive methods
298 require_once 'api/v3/utils.php';
299 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
301 'IP' => $_SERVER['REMOTE_ADDR'],
302 'level' => 'security',
303 'referer' => $_SERVER['HTTP_REFERER'],
304 'reason' => 'Destructive HTTP GET',
309 // trap all fatal errors
310 $errorScope = CRM_Core_TemporaryErrorScope
::create([
314 $result = civicrm_api($args[1], $args[2], $params);
317 if ($result === FALSE) {
318 return self
::error('Unknown error.');
324 * @return array|mixed|null
326 public static function &buildParamList() {
327 $requestParams = CRM_Utils_Request
::exportValues();
339 if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
340 $params = json_decode($requestParams['json'], TRUE);
341 if ($params === NULL) {
342 CRM_Utils_JSON
::output([
344 0 => 'error_message',
345 1 => 'Unable to decode supplied JSON.',
349 foreach ($requestParams as $n => $v) {
350 if (!array_key_exists($n, $skipVars)) {
354 if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) {
355 foreach ($requestParams['return'] as $key => $v) {
356 $params['return.' . $key] = 1;
365 public static function fatal($pearError) {
366 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/xml');
368 $error['code'] = $pearError->getCode();
369 $error['error_message'] = $pearError->getMessage();
370 $error['mode'] = $pearError->getMode();
371 $error['debug_info'] = $pearError->getDebugInfo();
372 $error['type'] = $pearError->getType();
373 $error['user_info'] = $pearError->getUserInfo();
374 $error['to_string'] = $pearError->toString();
375 $error['is_error'] = 1;
377 echo self
::output($error);
379 CRM_Utils_System
::civiExit();
383 * used to load a template "inline", eg. for ajax, without having to build a menu for each template
385 public static function loadTemplate() {
386 $request = CRM_Utils_Request
::retrieve('q', 'String');
387 if (FALSE !== strpos($request, '..')) {
388 die("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
391 $request = explode('/', $request);
392 $entity = _civicrm_api_get_camel_name($request[2]);
393 $tplfile = _civicrm_api_get_camel_name($request[3]);
395 $tpl = 'CRM/' . $entity . '/Page/Inline/' . $tplfile . '.tpl';
396 $smarty = CRM_Core_Smarty
::singleton();
397 CRM_Utils_System
::setTitle("$entity::$tplfile inline $tpl");
398 if (!$smarty->template_exists($tpl)) {
399 CRM_Utils_System
::setHttpHeader("Status", "404 Not Found");
400 die("Can't find the requested template file templates/$tpl");
402 if (array_key_exists('id', $_GET)) {// special treatmenent, because it's often used
403 $smarty->assign('id', (int) $_GET['id']);// an id is always positive
405 $pos = strpos(implode(array_keys($_GET)), '<');
407 if ($pos !== FALSE) {
408 die("SECURITY FATAL: one of the param names contains <");
410 $param = array_map('htmlentities', $_GET);
412 $smarty->assign_by_ref("request", $param);
414 if (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
415 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
418 $smarty->assign('tplFile', $tpl);
419 $config = CRM_Core_Config
::singleton();
420 $content = $smarty->fetch('CRM/common/' . strtolower($config->userFramework
) . '.tpl');
422 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region
::instance('html-header', FALSE)) {
423 CRM_Utils_System
::addHTMLHead($region->render(''));
425 CRM_Utils_System
::appendTPLFile($tpl, $content);
427 return CRM_Utils_System
::theme($content);
431 $content = "<!-- .tpl file embedded: $tpl -->\n";
432 CRM_Utils_System
::appendTPLFile($tpl, $content);
433 echo $content . $smarty->fetch($tpl);
434 CRM_Utils_System
::civiExit();
439 * This is a wrapper so you can call an api via json (it returns json too)
440 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}}
441 * to take all the emails from individuals.
442 * Works for POST & GET (POST recommended).
444 public static function ajaxJson() {
445 $requestParams = CRM_Utils_Request
::exportValues();
447 require_once 'api/v3/utils.php';
448 $config = CRM_Core_Config
::singleton();
449 if (!$config->debug
&& (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
450 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
453 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
455 'IP' => $_SERVER['REMOTE_ADDR'],
456 'level' => 'security',
457 'referer' => $_SERVER['HTTP_REFERER'],
458 'reason' => 'CSRF suspected',
461 CRM_Utils_JSON
::output($error);
463 if (empty($requestParams['entity'])) {
464 CRM_Utils_JSON
::output(civicrm_api3_create_error('missing entity param'));
466 if (empty($requestParams['entity'])) {
467 CRM_Utils_JSON
::output(civicrm_api3_create_error('missing entity entity'));
469 if (!empty($requestParams['json'])) {
470 $params = json_decode($requestParams['json'], TRUE);
472 $entity = CRM_Utils_String
::munge(CRM_Utils_Array
::value('entity', $requestParams));
473 $action = CRM_Utils_String
::munge(CRM_Utils_Array
::value('action', $requestParams));
474 if (!is_array($params)) {
475 CRM_Utils_JSON
::output([
477 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}',
481 $params['check_permissions'] = TRUE;
482 $params['version'] = 3;
483 $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
484 if (!$params['sequential']) {
485 $params['sequential'] = 1;
488 // trap all fatal errors
489 $errorScope = CRM_Core_TemporaryErrorScope
::create([
493 $result = civicrm_api($entity, $action, $params);
496 echo self
::output($result);
498 CRM_Utils_System
::civiExit();
506 public static function ajax() {
507 $requestParams = CRM_Utils_Request
::exportValues();
509 // this is driven by the menu system, so we can use permissioning to
510 // restrict calls to this etc
511 // the request has to be sent by an ajax call. First line of protection against csrf
512 $config = CRM_Core_Config
::singleton();
513 if (!$config->debug
&&
514 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
515 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
518 require_once 'api/v3/utils.php';
519 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
521 'IP' => $_SERVER['REMOTE_ADDR'],
522 'level' => 'security',
523 'referer' => $_SERVER['HTTP_REFERER'],
524 'reason' => 'CSRF suspected',
527 CRM_Utils_JSON
::output($error);
530 $q = CRM_Utils_Array
::value('fnName', $requestParams);
532 $entity = CRM_Utils_Array
::value('entity', $requestParams);
533 $action = CRM_Utils_Array
::value('action', $requestParams);
534 if (!$entity ||
!$action) {
536 'error_message' => 'missing mandatory params "entity=" or "action="',
539 echo self
::output($err);
540 CRM_Utils_System
::civiExit();
542 $args = ['civicrm', $entity, $action];
545 $args = explode('/', $q);
548 // get the class name, since all ajax functions pass className
549 $className = CRM_Utils_Array
::value('className', $requestParams);
551 // If the function isn't in the civicrm namespace, reject the request.
552 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
553 return self
::error('Unknown function invocation.');
556 // Support for multiple api calls
557 if (isset($entity) && $entity === 'api3') {
558 $result = self
::processMultiple();
561 $result = self
::process($args, self
::buildParamList());
564 echo self
::output($result);
566 CRM_Utils_System
::civiExit();
570 * Callback for multiple ajax api calls from CRM.api3()
573 public static function processMultiple() {
575 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
581 $output[$key] = self
::process($args, CRM_Utils_Array
::value(2, $call, []));
588 * NULL if execution should proceed; array if the response is already known
590 public function loadCMSBootstrap() {
591 $requestParams = CRM_Utils_Request
::exportValues();
592 $q = CRM_Utils_Array
::value('q', $requestParams);
593 $args = explode('/', $q);
595 // Proceed with bootstrap for "?entity=X&action=Y"
596 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
598 if (count($args) == 2 && $args[1] == 'ping') {
599 CRM_Utils_System
::loadBootStrap([], FALSE, FALSE);
600 return NULL; // this is pretty wonky but maybe there's some reason I can't see
602 if (count($args) != 3) {
603 return self
::error('ERROR: Malformed REST path');
605 if ($args[0] != 'civicrm') {
606 return self
::error('ERROR: Malformed REST path');
608 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
611 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
612 // FIXME: At time of writing, this doesn't actually do anything because
613 // authenticateKey abends, but that's a bad behavior which sends a
614 // malformed response.
615 CRM_Utils_System
::loadBootStrap([], FALSE, FALSE);
616 return self
::error('Failed to authenticate key');
622 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
623 if (empty($api_key)) {
624 CRM_Utils_System
::loadBootStrap([], FALSE, FALSE);
625 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
627 $contact_id = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
629 $uid = CRM_Core_BAO_UFMatch
::getUFId($contact_id);
633 if ($uid && $contact_id) {
634 CRM_Utils_System
::loadBootStrap(['uid' => $uid], TRUE, FALSE);
635 $session = CRM_Core_Session
::singleton();
636 $session->set('ufID', $uid);
637 $session->set('userID', $contact_id);
638 CRM_Core_DAO
::executeQuery('SET @civicrm_user_id = %1',
639 [1 => [$contact_id, 'Integer']]
644 CRM_Utils_System
::loadBootStrap([], FALSE, FALSE);
645 return self
::error('ERROR: No CMS user associated with given api-key');