3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Utils_REST
{
38 * Number of seconds we should let a REST process idle
40 static $rest_timeout = 0;
43 * Cache the actual UF Class
48 * Class constructor. This caches the real user framework class locally,
49 * so we can use it for authentication and validation.
51 * @internal param string $uf The userframework class
53 public function __construct() {
54 // any external program which call Rest Server is responsible for
55 // creating and attaching the session
56 $args = func_get_args();
57 $this->ufClass
= array_shift($args);
61 * Simple ping function to test for liveness.
64 * The string to be echoed.
68 public static function ping($var = NULL) {
69 $session = CRM_Core_Session
::singleton();
70 $key = $session->get('key');
71 //$session->set( 'key', $var );
72 return self
::simple(array('message' => "PONG: $key"));
76 * Generates values needed for error messages.
77 * @param string $message
81 public static function error($message = 'Unknown Error') {
83 'error_message' => $message,
90 * Generates values needed for non-error responses.
91 * @param array $params
95 public static function simple($params) {
96 $values = array('is_error' => 0);
104 public function run() {
105 $result = self
::handle();
106 return self
::output($result);
112 public function bootAndRun() {
113 $response = $this->loadCMSBootstrap();
114 if (is_array($response)) {
115 return self
::output($response);
125 public static function output(&$result) {
126 $requestParams = CRM_Utils_Request
::exportValues();
129 if (is_scalar($result)) {
133 $result = self
::simple(array('result' => $result));
135 elseif (is_array($result)) {
136 if (CRM_Utils_Array
::isHierarchical($result)) {
139 elseif (!array_key_exists('is_error', $result)) {
140 $result['is_error'] = 0;
144 $result = self
::error('Could not interpret return values from function.');
147 if (!empty($requestParams['json'])) {
148 header('Content-Type: application/json');
149 $json = json_encode(array_merge($result));
150 if (!empty($requestParams['prettyprint'])) {
151 // Used by the api explorer
152 return self
::jsonFormated($json);
157 if (isset($result['count'])) {
158 $count = ' count="' . $result['count'] . '" ';
163 $xml = "<?xml version=\"1.0\"?>
164 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
166 // check if this is a single element result (contact_get etc)
169 foreach ($result['values'] as $n => $v) {
170 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($v) . "</Result>\n";
174 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($result) . "</Result>\n";
177 $xml .= "</ResultSet>\n";
186 public static function jsonFormated($json) {
196 for ($i = 0; $i < strlen($json); $i++
) {
212 $result .= $char . $newline . str_repeat($tab, $tabcount);
222 $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
227 if ($inquote ||
$inarray) {
231 $result .= $char . $newline . str_repeat($tab, $tabcount);
236 $inquote = !$inquote;
269 public static function handle() {
270 $requestParams = CRM_Utils_Request
::exportValues();
272 // Get the function name being called from the q parameter in the query string
273 $q = CRM_Utils_array
::value('q', $requestParams);
274 // or for the rest interface, from fnName
275 $r = CRM_Utils_array
::value('fnName', $requestParams);
279 $entity = CRM_Utils_array
::value('entity', $requestParams);
280 if (empty($entity) && !empty($q)) {
281 $args = explode('/', $q);
282 // If the function isn't in the civicrm namespace, reject the request.
283 if ($args[0] != 'civicrm') {
284 return self
::error('Unknown function invocation.');
287 // If the query string is malformed, reject the request.
288 // Does this mean it will reject it
289 if ((count($args) != 3) && ($args[1] != 'ping')) {
290 return self
::error('Unknown function invocation.');
294 if ($args[1] == 'ping') {
299 // or the new format (entity+action)
301 $args[0] = 'civicrm';
302 $args[1] = CRM_Utils_array
::value('entity', $requestParams);
303 $args[2] = CRM_Utils_array
::value('action', $requestParams);
306 // Everyone should be required to provide the server key, so the whole
307 // interface can be disabled in more change to the configuration file.
308 // first check for civicrm site key
309 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
310 $docLink = CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
311 $key = CRM_Utils_array
::value('key', $requestParams);
313 return self
::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
315 return self
::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
318 // At this point we know we are not calling ping which does not require authentication.
319 // Therefore, at this point we need to make sure we're working with a trusted user.
320 // Valid users are those who provide a valid server key and API key
324 // Check and see if a valid secret API key is provided.
325 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
326 if (!$api_key ||
strtolower($api_key) == 'null') {
327 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
329 $valid_user = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
331 // If we didn't find a valid user, die
332 if (empty($valid_user)) {
333 return self
::error("User API key invalid");
336 return self
::process($args, self
::buildParamList());
341 * @param array $params
345 public static function process(&$args, $params) {
346 $params['check_permissions'] = TRUE;
347 $fnName = $apiFile = NULL;
348 // clean up all function / class names. they should be alphanumeric and _ only
349 for ($i = 1; $i <= 3; $i++
) {
350 if (!empty($args[$i])) {
351 $args[$i] = CRM_Utils_String
::munge($args[$i]);
355 // incase of ajax functions className is passed in url
356 if (isset($params['className'])) {
357 $params['className'] = CRM_Utils_String
::munge($params['className']);
359 // functions that are defined only in AJAX.php can be called via
361 if (!CRM_Core_Page_AJAX
::checkAuthz('method', $params['className'], $params['fnName'])) {
362 return self
::error('Unknown function invocation.');
365 return call_user_func(array($params['className'], $params['fnName']), $params);
368 if (!array_key_exists('version', $params)) {
369 $params['version'] = 3;
372 if ($params['version'] == 2) {
373 $result['is_error'] = 1;
374 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
375 $result['deprecated'] = "Please upgrade to API v3";
379 if ($_SERVER['REQUEST_METHOD'] == 'GET' && strtolower(substr($args[2], 0, 3)) != 'get') {
380 // get only valid for non destructive methods
381 require_once 'api/v3/utils.php';
382 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
384 'IP' => $_SERVER['REMOTE_ADDR'],
385 'level' => 'security',
386 'referer' => $_SERVER['HTTP_REFERER'],
387 'reason' => 'Destructive HTTP GET',
392 // trap all fatal errors
393 $errorScope = CRM_Core_TemporaryErrorScope
::create(array('CRM_Utils_REST', 'fatal'));
394 $result = civicrm_api($args[1], $args[2], $params);
397 if ($result === FALSE) {
398 return self
::error('Unknown error.');
404 * @return array|mixed|null
406 public static function &buildParamList() {
407 $requestParams = CRM_Utils_Request
::exportValues();
419 if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
420 $params = json_decode($requestParams['json'], TRUE);
421 if ($params === NULL) {
422 CRM_Utils_JSON
::output(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
425 foreach ($requestParams as $n => $v) {
426 if (!array_key_exists($n, $skipVars)) {
430 if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) {
431 foreach ($requestParams['return'] as $key => $v) {
432 $params['return.' . $key] = 1;
441 public static function fatal($pearError) {
442 header('Content-Type: text/xml');
444 $error['code'] = $pearError->getCode();
445 $error['error_message'] = $pearError->getMessage();
446 $error['mode'] = $pearError->getMode();
447 $error['debug_info'] = $pearError->getDebugInfo();
448 $error['type'] = $pearError->getType();
449 $error['user_info'] = $pearError->getUserInfo();
450 $error['to_string'] = $pearError->toString();
451 $error['is_error'] = 1;
453 echo self
::output($error);
455 CRM_Utils_System
::civiExit();
459 * used to load a template "inline", eg. for ajax, without having to build a menu for each template
461 public static function loadTemplate() {
462 $request = CRM_Utils_Request
::retrieve('q', 'String');
463 if (FALSE !== strpos($request, '..')) {
464 die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
467 $request = explode('/', $request);
468 $entity = _civicrm_api_get_camel_name($request[2]);
469 $tplfile = _civicrm_api_get_camel_name($request[3]);
471 $tpl = 'CRM/' . $entity . '/Page/Inline/' . $tplfile . '.tpl';
472 $smarty = CRM_Core_Smarty
::singleton();
473 CRM_Utils_System
::setTitle("$entity::$tplfile inline $tpl");
474 if (!$smarty->template_exists($tpl)) {
475 header("Status: 404 Not Found");
476 die ("Can't find the requested template file templates/$tpl");
478 if (array_key_exists('id', $_GET)) {// special treatmenent, because it's often used
479 $smarty->assign('id', (int) $_GET['id']);// an id is always positive
481 $pos = strpos(implode(array_keys($_GET)), '<');
483 if ($pos !== FALSE) {
484 die ("SECURITY FATAL: one of the param names contains <");
486 $param = array_map('htmlentities', $_GET);
488 $smarty->assign_by_ref("request", $param);
490 if (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
491 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
494 $smarty->assign('tplFile', $tpl);
495 $config = CRM_Core_Config
::singleton();
496 $content = $smarty->fetch('CRM/common/' . strtolower($config->userFramework
) . '.tpl');
498 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region
::instance('html-header', FALSE)) {
499 CRM_Utils_System
::addHTMLHead($region->render(''));
501 CRM_Utils_System
::appendTPLFile($tpl, $content);
503 return CRM_Utils_System
::theme($content);
507 $content = "<!-- .tpl file embeded: $tpl -->\n";
508 CRM_Utils_System
::appendTPLFile($tpl, $content);
509 echo $content . $smarty->fetch($tpl);
510 CRM_Utils_System
::civiExit();
515 * This is a wrapper so you can call an api via json (it returns json too)
516 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals
517 * works for POST & GET (POST recommended)
519 public static function ajaxJson() {
520 $requestParams = CRM_Utils_Request
::exportValues();
522 require_once 'api/v3/utils.php';
523 // Why is $config undefined -- $config = CRM_Core_Config::singleton();
524 if (!$config->debug
&& (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
525 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
528 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
530 'IP' => $_SERVER['REMOTE_ADDR'],
531 'level' => 'security',
532 'referer' => $_SERVER['HTTP_REFERER'],
533 'reason' => 'CSRF suspected',
536 CRM_Utils_JSON
::output($error);
538 if (empty($requestParams['entity'])) {
539 CRM_Utils_JSON
::output(civicrm_api3_create_error('missing entity param'));
541 if (empty($requestParams['entity'])) {
542 CRM_Utils_JSON
::output(civicrm_api3_create_error('missing entity entity'));
544 if (!empty($requestParams['json'])) {
545 $params = json_decode($requestParams['json'], TRUE);
547 $entity = CRM_Utils_String
::munge(CRM_Utils_Array
::value('entity', $requestParams));
548 $action = CRM_Utils_String
::munge(CRM_Utils_Array
::value('action', $requestParams));
549 if (!is_array($params)) {
550 CRM_Utils_JSON
::output(array(
552 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}',
556 $params['check_permissions'] = TRUE;
557 $params['version'] = 3;
558 $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
559 if (!$params['sequential']) {
560 $params['sequential'] = 1;
563 // trap all fatal errors
564 $errorScope = CRM_Core_TemporaryErrorScope
::create(array('CRM_Utils_REST', 'fatal'));
565 $result = civicrm_api($entity, $action, $params);
568 echo self
::output($result);
570 CRM_Utils_System
::civiExit();
578 public static function ajax() {
579 $requestParams = CRM_Utils_Request
::exportValues();
581 // this is driven by the menu system, so we can use permissioning to
582 // restrict calls to this etc
583 // the request has to be sent by an ajax call. First line of protection against csrf
584 $config = CRM_Core_Config
::singleton();
585 if (!$config->debug
&&
586 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
587 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
590 require_once 'api/v3/utils.php';
591 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
593 'IP' => $_SERVER['REMOTE_ADDR'],
594 'level' => 'security',
595 'referer' => $_SERVER['HTTP_REFERER'],
596 'reason' => 'CSRF suspected',
599 CRM_Utils_JSON
::output($error);
602 $q = CRM_Utils_Array
::value('fnName', $requestParams);
604 $entity = CRM_Utils_Array
::value('entity', $requestParams);
605 $action = CRM_Utils_Array
::value('action', $requestParams);
606 if (!$entity ||
!$action) {
607 $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
608 echo self
::output($err);
609 CRM_Utils_System
::civiExit();
611 $args = array('civicrm', $entity, $action);
614 $args = explode('/', $q);
617 // get the class name, since all ajax functions pass className
618 $className = CRM_Utils_Array
::value('className', $requestParams);
620 // If the function isn't in the civicrm namespace, reject the request.
621 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
622 return self
::error('Unknown function invocation.');
625 // Support for multiple api calls
626 if (isset($entity) && $entity === 'api3') {
627 $result = self
::processMultiple();
630 $result = self
::process($args, self
::buildParamList());
633 echo self
::output($result);
635 CRM_Utils_System
::civiExit();
639 * Callback for multiple ajax api calls from CRM.api3()
642 public static function processMultiple() {
644 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
650 $output[$key] = self
::process($args, CRM_Utils_Array
::value(2, $call, array()));
657 * NULL if execution should proceed; array if the response is already known
659 public function loadCMSBootstrap() {
660 $requestParams = CRM_Utils_Request
::exportValues();
661 $q = CRM_Utils_array
::value('q', $requestParams);
662 $args = explode('/', $q);
664 // Proceed with bootstrap for "?entity=X&action=Y"
665 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
667 if (count($args) == 2 && $args[1] == 'ping') {
668 return NULL; // this is pretty wonky but maybe there's some reason I can't see
670 if (count($args) != 3) {
671 return self
::error('ERROR: Malformed REST path');
673 if ($args[0] != 'civicrm') {
674 return self
::error('ERROR: Malformed REST path');
676 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
679 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
680 // FIXME: At time of writing, this doesn't actually do anything because
681 // authenticateKey abends, but that's a bad behavior which sends a
682 // malformed response.
683 return self
::error('Failed to authenticate key');
689 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
690 if (empty($api_key)) {
691 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
693 $contact_id = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
695 $uid = CRM_Core_BAO_UFMatch
::getUFId($contact_id);
700 CRM_Utils_System
::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
704 return self
::error('ERROR: No CMS user associated with given api-key');