3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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
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) {
106 $requestParams = CRM_Utils_Request
::exportValues();
109 if (is_scalar($result)) {
113 $result = self
::simple(array('result' => $result));
115 elseif (is_array($result)) {
116 if (CRM_Utils_Array
::isHierarchical($result)) {
119 elseif (!array_key_exists('is_error', $result)) {
120 $result['is_error'] = 0;
124 $result = self
::error('Could not interpret return values from function.');
127 if (CRM_Utils_Array
::value('json', $requestParams)) {
128 header('Content-Type: text/javascript');
129 $json = json_encode(array_merge($result));
130 if (CRM_Utils_Array
::value('prettyprint', $requestParams)) {
131 return self
::jsonFormated($json);
137 if (isset($result['count'])) {
140 $count = ' count="' . $result['count'] . '" ';
145 $xml = "<?xml version=\"1.0\"?>
146 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
148 // check if this is a single element result (contact_get etc)
151 foreach ($result['values'] as $n => $v) {
152 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($v) . "</Result>\n";
156 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($result) . "</Result>\n";
159 $xml .= "</ResultSet>\n";
163 static function jsonFormated($json) {
173 for ($i = 0; $i < strlen($json); $i++
) {
189 $result .= $char . $newline . str_repeat($tab, $tabcount);
199 $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
204 if ($inquote ||
$inarray) {
207 else $result .= $char . $newline . str_repeat($tab, $tabcount);
211 $inquote = !$inquote;
241 static function handle() {
242 $requestParams = CRM_Utils_Request
::exportValues();
244 // Get the function name being called from the q parameter in the query string
245 $q = CRM_Utils_array
::value('q', $requestParams);
246 // or for the rest interface, from fnName
247 $r = CRM_Utils_array
::value('fnName', $requestParams);
252 $args = explode('/', $q);
253 // If the function isn't in the civicrm namespace, reject the request.
254 if ($args[0] != 'civicrm') {
255 return self
::error('Unknown function invocation.');
258 // If the query string is malformed, reject the request.
259 // Does this mean it will reject it
260 if ((count($args) != 3) && ($args[1] != 'ping')) {
261 return self
::error('Unknown function invocation.');
265 if ($args[1] == 'ping') {
269 // or the new format (entity+action)
271 $args[0] = 'civicrm';
272 $args[1] = CRM_Utils_array
::value('entity', $requestParams);
273 $args[2] = CRM_Utils_array
::value('action', $requestParams);
277 // Everyone should be required to provide the server key, so the whole
278 // interface can be disabled in more change to the configuration file.
279 // first check for civicrm site key
280 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
281 $docLink = CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
282 $key = CRM_Utils_array
::value('key', $requestParams);
284 return self
::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
286 return self
::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
290 // At this point we know we are not calling ping which does not require authentication.
291 // Therefore, at this point we need to make sure we're working with a trusted user.
292 // Valid users are those who provide a valid server key and API key
296 // Check and see if a valid secret API key is provided.
297 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
298 if (!$api_key ||
strtolower($api_key) == 'null') {
299 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
301 $valid_user = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
303 // If we didn't find a valid user, die
304 if (empty($valid_user)) {
305 return self
::error("User API key invalid");
308 return self
::process($args, self
::buildParamList());
311 static function process(&$args, $params) {
312 $params['check_permissions'] = TRUE;
313 $fnName = $apiFile = NULL;
314 // clean up all function / class names. they should be alphanumeric and _ only
315 for ($i = 1; $i <= 3; $i++
) {
316 if (!empty($args[$i])) {
317 $args[$i] = CRM_Utils_String
::munge($args[$i]);
321 // incase of ajax functions className is passed in url
322 if (isset($params['className'])) {
323 $params['className'] = CRM_Utils_String
::munge($params['className']);
325 // functions that are defined only in AJAX.php can be called via
327 if (!CRM_Core_Page_AJAX
::checkAuthz('method', $params['className'], $params['fnName'])) {
328 return self
::error('Unknown function invocation.');
331 return call_user_func(array($params['className'], $params['fnName']), $params);
334 if (!array_key_exists('version', $params)) {
335 $params['version'] = 3;
338 if ($params['version'] == 2) {
339 $result['is_error'] = 1;
340 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
341 $result['deprecated'] = "Please upgrade to API v3";
345 if ($_SERVER['REQUEST_METHOD'] == 'GET' && strtolower(substr( $args[2],0,3)) != 'get') {
346 // get only valid for non destructive methods
347 require_once 'api/v3/utils.php';
348 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
350 'IP' => $_SERVER['REMOTE_ADDR'],
351 'level' => 'security',
352 'referer' => $_SERVER['HTTP_REFERER'],
353 'reason' => 'Destructive HTTP GET',
358 // trap all fatal errors
359 $errorScope = CRM_Core_TemporaryErrorScope
::create(array('CRM_Utils_REST', 'fatal'));
360 $result = civicrm_api($args[1], $args[2], $params);
363 if ($result === FALSE) {
364 return self
::error('Unknown error.');
369 static function &buildParamList() {
370 $requestParams = CRM_Utils_Request
::exportValues();
382 if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
383 $params = json_decode($requestParams['json'], TRUE);
384 if($params === NULL) {
385 echo json_encode(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
386 CRM_Utils_System
::civiExit();
389 foreach ($requestParams as $n => $v) {
390 if (!array_key_exists($n, $skipVars)) {
394 if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) {
395 foreach ($requestParams['return'] as $key => $v) $params['return.' . $key] = 1;
400 static function fatal($pearError) {
401 header('Content-Type: text/xml');
403 $error['code'] = $pearError->getCode();
404 $error['error_message'] = $pearError->getMessage();
405 $error['mode'] = $pearError->getMode();
406 $error['debug_info'] = $pearError->getDebugInfo();
407 $error['type'] = $pearError->getType();
408 $error['user_info'] = $pearError->getUserInfo();
409 $error['to_string'] = $pearError->toString();
410 $error['is_error'] = 1;
412 echo self
::output($error);
414 CRM_Utils_System
::civiExit();
417 static function APIDoc() {
419 CRM_Utils_System
::setTitle("API Parameters");
420 $template = CRM_Core_Smarty
::singleton();
421 return CRM_Utils_System
::theme(
422 $template->fetch('CRM/Core/APIDoc.tpl')
426 static function ajaxDoc() {
427 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/api/explorer'));
430 /** used to load a template "inline", eg. for ajax, without having to build a menu for each template */
431 static function loadTemplate () {
432 $request = CRM_Utils_Request
::retrieve( 'q', 'String');
433 if (false !== strpos($request, '..')) {
434 die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
437 $request = split ('/',$request);
438 $entity = _civicrm_api_get_camel_name($request[2]);
439 $tplfile=_civicrm_api_get_camel_name($request[3]);
441 $tpl = 'CRM/'.$entity.'/Page/Inline/'.$tplfile.'.tpl';
442 $smarty= CRM_Core_Smarty
::singleton( );
443 CRM_Utils_System
::setTitle( "$entity::$tplfile inline $tpl" );
444 if( !$smarty->template_exists($tpl) ){
445 header("Status: 404 Not Found");
446 die ("Can't find the requested template file templates/$tpl");
448 if (array_key_exists('id',$_GET)) {// special treatmenent, because it's often used
449 $smarty->assign ('id',(int)$_GET['id']);// an id is always positive
451 $pos = strpos (implode (array_keys ($_GET)),'<') ;
453 if ($pos !== false) {
454 die ("SECURITY FATAL: one of the param names contains <");
456 $param = array_map( 'htmlentities' , $_GET);
458 $smarty->assign_by_ref("request", $param);
460 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
461 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
463 $smarty->assign( 'tplFile', $tpl );
464 $config = CRM_Core_Config
::singleton();
465 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework
) .'.tpl' );
467 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region
::instance('html-header', FALSE)) {
468 CRM_Utils_System
::addHTMLHead($region->render(''));
470 CRM_Utils_System
::appendTPLFile( $tpl, $content );
472 return CRM_Utils_System
::theme($content);
475 $content = "<!-- .tpl file embeded: $tpl -->\n";
476 CRM_Utils_System
::appendTPLFile( $tpl, $content );
477 echo $content . $smarty->fetch ($tpl);
478 CRM_Utils_System
::civiExit( );
482 /** This is a wrapper so you can call an api via json (it returns json too)
483 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals
484 * works for POST & GET (POST recommended)
486 static function ajaxJson() {
487 $requestParams = CRM_Utils_Request
::exportValues();
489 require_once 'api/v3/utils.php';
490 // Why is $config undefined -- $config = CRM_Core_Config::singleton();
491 if (!$config->debug
&& (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
492 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
494 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
496 'IP' => $_SERVER['REMOTE_ADDR'],
497 'level' => 'security',
498 'referer' => $_SERVER['HTTP_REFERER'],
499 'reason' => 'CSRF suspected',
502 echo json_encode($error);
503 CRM_Utils_System
::civiExit();
505 if (empty($requestParams['entity'])) {
506 echo json_encode(civicrm_api3_create_error('missing entity param'));
507 CRM_Utils_System
::civiExit();
509 if (empty($requestParams['entity'])) {
510 echo json_encode(civicrm_api3_create_error('missing entity entity'));
511 CRM_Utils_System
::civiExit();
513 if (!empty($requestParams['json'])) {
514 $params = json_decode($requestParams['json'], TRUE);
516 $entity = CRM_Utils_String
::munge(CRM_Utils_Array
::value('entity', $requestParams));
517 $action = CRM_Utils_String
::munge(CRM_Utils_Array
::value('action', $requestParams));
518 if (!is_array($params)) {
519 echo json_encode(array('is_error' => 1, 'error_message', 'invalid json format: ?{"param_with_double_quote":"value"}'));
520 CRM_Utils_System
::civiExit();
523 $params['check_permissions'] = TRUE;
524 $params['version'] = 3;
525 $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
526 if (!$params['sequential']) {
527 $params['sequential'] = 1;
530 // trap all fatal errors
531 $errorScope = CRM_Core_TemporaryErrorScope
::create(array('CRM_Utils_REST', 'fatal'));
532 $result = civicrm_api($entity, $action, $params);
535 echo self
::output($result);
537 CRM_Utils_System
::civiExit();
540 static function ajax() {
541 $requestParams = CRM_Utils_Request
::exportValues();
543 // this is driven by the menu system, so we can use permissioning to
544 // restrict calls to this etc
545 // the request has to be sent by an ajax call. First line of protection against csrf
546 $config = CRM_Core_Config
::singleton();
547 if (!$config->debug
&&
548 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
549 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
552 require_once 'api/v3/utils.php';
553 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
555 'IP' => $_SERVER['REMOTE_ADDR'],
556 'level' => 'security',
557 'referer' => $_SERVER['HTTP_REFERER'],
558 'reason' => 'CSRF suspected',
561 echo json_encode($error);
562 CRM_Utils_System
::civiExit();
565 $q = CRM_Utils_Array
::value('fnName', $requestParams);
567 $entity = CRM_Utils_Array
::value('entity', $requestParams);
568 $action = CRM_Utils_Array
::value('action', $requestParams);
569 if (!$entity ||
!$action) {
570 $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
571 echo self
::output($err);
572 CRM_Utils_System
::civiExit();
574 $args = array('civicrm', $entity, $action);
577 $args = explode('/', $q);
580 // get the class name, since all ajax functions pass className
581 $className = CRM_Utils_Array
::value('className', $requestParams);
583 // If the function isn't in the civicrm namespace, reject the request.
584 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
585 return self
::error('Unknown function invocation.');
588 // Support for multiple api calls
589 if (isset($entity) && $entity === 'api3') {
590 $result = self
::processMultiple();
593 $result = self
::process($args, self
::buildParamList());
596 echo self
::output($result);
598 CRM_Utils_System
::civiExit();
602 * Callback for multiple ajax api calls from CRM.api3()
605 static function processMultiple() {
607 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
613 $output[$key] = self
::process($args, CRM_Utils_Array
::value(2, $call, array()));
619 * @return array|NULL NULL if execution should proceed; array if the response is already known
621 function loadCMSBootstrap() {
622 $requestParams = CRM_Utils_Request
::exportValues();
623 $q = CRM_Utils_array
::value('q', $requestParams);
624 $args = explode('/', $q);
626 // Proceed with bootstrap for "?entity=X&action=Y"
627 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
629 if (count($args) == 2 && $args[1] == 'ping') {
630 return NULL; // this is pretty wonky but maybe there's some reason I can't see
632 if (count($args) != 3) {
633 return self
::error('ERROR: Malformed REST path');
635 if ($args[0] != 'civicrm') {
636 return self
::error('ERROR: Malformed REST path');
638 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
641 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
642 // FIXME: At time of writing, this doesn't actually do anything because
643 // authenticateKey abends, but that's a bad behavior which sends a
644 // malformed response.
645 return self
::error('Failed to authenticate key');
651 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
652 if (empty($api_key)) {
653 return self
::error("FATAL: mandatory param 'api_key' (user key) missing");
655 $contact_id = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
657 $uid = CRM_Core_BAO_UFMatch
::getUFId($contact_id);
662 CRM_Utils_System
::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
666 return self
::error('ERROR: No CMS user associated with given api-key');