3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Utils_REST
{
38 * Number of seconds we should let a REST process idle
41 static $rest_timeout = 0;
44 * Cache the actual UF Class
49 * Class constructor. This caches the real user framework class locally,
50 * so we can use it for authentication and validation.
52 * @param string $uf The userframework class
54 public function __construct() {
55 // any external program which call Rest Server is responsible for
56 // creating and attaching the session
57 $args = func_get_args();
58 $this->ufClass
= array_shift($args);
62 * Simple ping function to test for liveness.
64 * @param string $var The string to be echoed
69 public static function ping($var = NULL) {
70 $session = CRM_Core_Session
::singleton();
71 $key = $session->get('key');
72 //$session->set( 'key', $var );
73 return self
::simple(array('message' => "PONG: $key"));
76 // Generates values needed for error messages
77 static function error($message = 'Unknown Error') {
79 'error_message' => $message,
85 // Generates values needed for non-error responses.
86 static function simple($params) {
87 $values = array('is_error' => 0);
93 $result = self
::handle();
94 return self
::output($result);
97 function bootAndRun() {
98 $response = $this->loadCMSBootstrap();
99 if (is_array($response)) {
100 return self
::output($response);
105 static function output(&$result) {
107 if (is_scalar($result)) {
111 $result = self
::simple(array('result' => $result));
113 elseif (is_array($result)) {
114 if (CRM_Utils_Array
::isHierarchical($result)) {
117 elseif (!array_key_exists('is_error', $result)) {
118 $result['is_error'] = 0;
122 $result = self
::error('Could not interpret return values from function.');
125 if (!empty($_REQUEST['json'])) {
126 header('Content-Type: text/javascript');
127 $json = json_encode(array_merge($result));
128 if (!empty($_REQUEST['debug'])) {
129 return self
::jsonFormated($json);
135 if (isset($result['count'])) {
138 $count = ' count="' . $result['count'] . '" ';
143 $xml = "<?xml version=\"1.0\"?>
144 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
146 // check if this is a single element result (contact_get etc)
149 foreach ($result['values'] as $n => $v) {
150 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($v) . "</Result>\n";
154 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($result) . "</Result>\n";
157 $xml .= "</ResultSet>\n";
161 static function jsonFormated($json) {
171 for ($i = 0; $i < strlen($json); $i++
) {
187 $result .= $char . $newline . str_repeat($tab, $tabcount);
197 $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
202 if ($inquote ||
$inarray) {
205 else $result .= $char . $newline . str_repeat($tab, $tabcount);
209 $inquote = !$inquote;
239 static function handle() {
240 // Get the function name being called from the q parameter in the query string
241 $q = CRM_Utils_array
::value('q', $_REQUEST);
242 // or for the rest interface, from fnName
243 $r = CRM_Utils_array
::value('fnName', $_REQUEST);
248 $args = explode('/', $q);
249 // If the function isn't in the civicrm namespace, reject the request.
250 if ($args[0] != 'civicrm') {
251 return self
::error('Unknown function invocation.');
254 // If the query string is malformed, reject the request.
255 // Does this mean it will reject it
256 if ((count($args) != 3) && ($args[1] != 'ping')) {
257 return self
::error('Unknown function invocation.');
261 if ($args[1] == 'ping') {
265 // or the new format (entity+action)
267 $args[0] = 'civicrm';
268 $args[1] = CRM_Utils_array
::value('entity', $_REQUEST);
269 $args[2] = CRM_Utils_array
::value('action', $_REQUEST);
273 // Everyone should be required to provide the server key, so the whole
274 // interface can be disabled in more change to the configuration file.
275 // first check for civicrm site key
276 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
277 $docLink = CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
278 $key = CRM_Utils_array
::value('key', $_REQUEST);
280 return self
::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
282 return self
::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
286 // At this point we know we are not calling ping which does not require authentication.
287 // Therefore, at this point we need to make sure we're working with a trusted user.
288 // Valid users are those who provide a valid server key and API key
292 // Check and see if a valid secret API key is provided.
293 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
294 if (!$api_key ||
strtolower($api_key) == 'null') {
295 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
297 $valid_user = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
299 // If we didn't find a valid user, die
300 if (empty($valid_user)) {
301 return self
::error("User API key invalid");
304 return self
::process($args, self
::buildParamList());
307 static function process(&$args, $params) {
308 $params['check_permissions'] = TRUE;
309 $fnName = $apiFile = NULL;
310 // clean up all function / class names. they should be alphanumeric and _ only
311 for ($i = 1; $i <= 3; $i++
) {
312 if (!empty($args[$i])) {
313 $args[$i] = CRM_Utils_String
::munge($args[$i]);
317 // incase of ajax functions className is passed in url
318 if (isset($params['className'])) {
319 $params['className'] = CRM_Utils_String
::munge($params['className']);
321 // functions that are defined only in AJAX.php can be called via
323 if (!CRM_Core_Page_AJAX
::checkAuthz('method', $params['className'], $params['fnName'])) {
324 return self
::error('Unknown function invocation.');
327 return call_user_func(array($params['className'], $params['fnName']), $params);
330 if (!array_key_exists('version', $params)) {
331 $params['version'] = 3;
334 if ($params['version'] == 2) {
335 $result['is_error'] = 1;
336 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
337 $result['deprecated'] = "Please upgrade to API v3";
341 if ($_SERVER['REQUEST_METHOD'] == 'GET' && strtolower(substr( $args[2],0,3)) != 'get') {
342 // get only valid for non destructive methods
343 require_once 'api/v3/utils.php';
344 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
346 'IP' => $_SERVER['REMOTE_ADDR'],
347 'level' => 'security',
348 'referer' => $_SERVER['HTTP_REFERER'],
349 'reason' => 'Destructive HTTP GET',
354 // trap all fatal errors
355 CRM_Core_Error
::setCallback(array('CRM_Utils_REST', 'fatal'));
356 $result = civicrm_api($args[1], $args[2], $params);
357 CRM_Core_Error
::setCallback();
359 if ($result === FALSE) {
360 return self
::error('Unknown error.');
365 static function &buildParamList() {
377 if (array_key_exists('json', $_REQUEST) && $_REQUEST['json'][0] == "{") {
378 $params = json_decode($_REQUEST['json'], TRUE);
379 if($params === NULL) {
380 echo json_encode(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
381 CRM_Utils_System
::civiExit();
384 foreach ($_REQUEST as $n => $v) {
385 if (!array_key_exists($n, $skipVars)) {
389 if (array_key_exists('return', $_REQUEST) && is_array($_REQUEST['return'])) {
390 foreach ($_REQUEST['return'] as $key => $v) $params['return.' . $key] = 1;
395 static function fatal($pearError) {
396 header('Content-Type: text/xml');
398 $error['code'] = $pearError->getCode();
399 $error['error_message'] = $pearError->getMessage();
400 $error['mode'] = $pearError->getMode();
401 $error['debug_info'] = $pearError->getDebugInfo();
402 $error['type'] = $pearError->getType();
403 $error['user_info'] = $pearError->getUserInfo();
404 $error['to_string'] = $pearError->toString();
405 $error['is_error'] = 1;
407 echo self
::output($error);
409 CRM_Utils_System
::civiExit();
412 static function APIDoc() {
414 CRM_Utils_System
::setTitle("API Parameters");
415 $template = CRM_Core_Smarty
::singleton();
416 return CRM_Utils_System
::theme(
417 $template->fetch('CRM/Core/APIDoc.tpl')
421 static function ajaxDoc() {
422 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/api/explorer'));
425 /** used to load a template "inline", eg. for ajax, without having to build a menu for each template */
426 static function loadTemplate () {
427 $request = CRM_Utils_Request
::retrieve( 'q', 'String');
428 if (false !== strpos($request, '..')) {
429 die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
432 $request = split ('/',$request);
433 $entity = _civicrm_api_get_camel_name($request[2]);
434 $tplfile=_civicrm_api_get_camel_name($request[3]);
436 $tpl = 'CRM/'.$entity.'/Page/Inline/'.$tplfile.'.tpl';
437 $smarty= CRM_Core_Smarty
::singleton( );
438 CRM_Utils_System
::setTitle( "$entity::$tplfile inline $tpl" );
439 if( !$smarty->template_exists($tpl) ){
440 header("Status: 404 Not Found");
441 die ("Can't find the requested template file templates/$tpl");
443 if (array_key_exists('id',$_GET)) {// special treatmenent, because it's often used
444 $smarty->assign ('id',(int)$_GET['id']);// an id is always positive
446 $pos = strpos (implode (array_keys ($_GET)),'<') ;
448 if ($pos !== false) {
449 die ("SECURITY FATAL: one of the param names contains <");
451 $param = array_map( 'htmlentities' , $_GET);
453 $smarty->assign_by_ref("request", $param);
455 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
456 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
458 $smarty->assign( 'tplFile', $tpl );
459 $config = CRM_Core_Config
::singleton();
460 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework
) .'.tpl' );
462 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region
::instance('html-header', FALSE)) {
463 CRM_Utils_System
::addHTMLHead($region->render(''));
465 CRM_Utils_System
::appendTPLFile( $tpl, $content );
467 return CRM_Utils_System
::theme($content);
470 $content = "<!-- .tpl file embeded: $tpl -->\n";
471 CRM_Utils_System
::appendTPLFile( $tpl, $content );
472 echo $content . $smarty->fetch ($tpl);
473 CRM_Utils_System
::civiExit( );
477 /** This is a wrapper so you can call an api via json (it returns json too)
478 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals
479 * works for POST & GET (POST recommended)
481 static function ajaxJson() {
482 require_once 'api/v3/utils.php';
483 if (!$config->debug
&& (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
484 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
486 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
488 'IP' => $_SERVER['REMOTE_ADDR'],
489 'level' => 'security',
490 'referer' => $_SERVER['HTTP_REFERER'],
491 'reason' => 'CSRF suspected',
494 echo json_encode($error);
495 CRM_Utils_System
::civiExit();
497 if (empty($_REQUEST['entity'])) {
498 echo json_encode(civicrm_api3_create_error('missing entity param'));
499 CRM_Utils_System
::civiExit();
501 if (empty($_REQUEST['entity'])) {
502 echo json_encode(civicrm_api3_create_error('missing entity entity'));
503 CRM_Utils_System
::civiExit();
505 if (!empty($_REQUEST['json'])) {
506 $params = json_decode($_REQUEST['json'], TRUE);
508 $entity = CRM_Utils_String
::munge(CRM_Utils_Array
::value('entity', $_REQUEST));
509 $action = CRM_Utils_String
::munge(CRM_Utils_Array
::value('action', $_REQUEST));
510 if (!is_array($params)) {
511 echo json_encode(array('is_error' => 1, 'error_message', 'invalid json format: ?{"param_with_double_quote":"value"}'));
512 CRM_Utils_System
::civiExit();
515 $params['check_permissions'] = TRUE;
516 $params['version'] = 3;
517 $_REQUEST['json'] = 1;
518 if (!$params['sequential']) {
519 $params['sequential'] = 1;
521 // trap all fatal errors
522 CRM_Core_Error
::setCallback(array('CRM_Utils_REST', 'fatal'));
523 $result = civicrm_api($entity, $action, $params);
525 CRM_Core_Error
::setCallback();
527 echo self
::output($result);
529 CRM_Utils_System
::civiExit();
532 static function ajax() {
533 // this is driven by the menu system, so we can use permissioning to
534 // restrict calls to this etc
535 // the request has to be sent by an ajax call. First line of protection against csrf
536 $config = CRM_Core_Config
::singleton();
537 if (!$config->debug
&&
538 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
539 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
542 require_once 'api/v3/utils.php';
543 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
545 'IP' => $_SERVER['REMOTE_ADDR'],
546 'level' => 'security',
547 'referer' => $_SERVER['HTTP_REFERER'],
548 'reason' => 'CSRF suspected',
551 echo json_encode($error);
552 CRM_Utils_System
::civiExit();
555 $q = CRM_Utils_Array
::value('fnName', $_REQUEST);
557 $entity = CRM_Utils_Array
::value('entity', $_REQUEST);
558 $action = CRM_Utils_Array
::value('action', $_REQUEST);
559 if (!$entity ||
!$action) {
560 $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
561 echo self
::output($err);
562 CRM_Utils_System
::civiExit();
564 $args = array('civicrm', $entity, $action);
567 $args = explode('/', $q);
570 // get the class name, since all ajax functions pass className
571 $className = CRM_Utils_Array
::value('className', $_REQUEST);
573 // If the function isn't in the civicrm namespace, reject the request.
574 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
575 return self
::error('Unknown function invocation.');
578 // Support for multiple api calls
579 if (isset($entity) && $entity === 'api3') {
580 $result = self
::processMultiple();
583 $result = self
::process($args, self
::buildParamList());
586 echo self
::output($result);
588 CRM_Utils_System
::civiExit();
592 * Callback for multiple ajax api calls from CRM.api3()
595 static function processMultiple() {
597 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
603 $output[$key] = self
::process($args, CRM_Utils_Array
::value(2, $call, array()));
609 * @return array|NULL NULL if execution should proceed; array if the response is already known
611 function loadCMSBootstrap() {
612 $q = CRM_Utils_array
::value('q', $_REQUEST);
613 $args = explode('/', $q);
615 // Proceed with bootstrap for "?entity=X&action=Y"
616 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
618 if (count($args) == 2 && $args[1] == 'ping') {
619 return NULL; // this is pretty wonky but maybe there's some reason I can't see
621 if (count($args) != 3) {
622 return self
::error('ERROR: Malformed REST path');
624 if ($args[0] != 'civicrm') {
625 return self
::error('ERROR: Malformed REST path');
627 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
630 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
631 // FIXME: At time of writing, this doesn't actually do anything because
632 // authenticateKey abends, but that's a bad behavior which sends a
633 // malformed response.
634 return self
::error('Failed to authenticate key');
640 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
641 if (empty($api_key)) {
642 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
644 $contact_id = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
646 $uid = CRM_Core_BAO_UFMatch
::getUFId($contact_id);
651 CRM_Utils_System
::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
655 return self
::error('ERROR: No CMS user associated with given api-key');