3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 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"));
77 * Authentication wrapper to the UF Class
79 * @param string $name Login name
80 * @param string $pass Password
82 * @return string The REST Client key
86 public static function authenticate($name, $pass) {
88 $result = CRM_Utils_System
::authenticate($name, $pass);
91 return self
::error('Could not authenticate user, invalid name or password.');
94 $session = CRM_Core_Session
::singleton();
95 $api_key = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $result[0], 'api_key');
97 if (empty($api_key)) {
98 // These two lines can be used to set the initial value of the key. A better means is needed.
99 //CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Contact', $result[0], 'api_key', sha1($result[2]) );
100 //$api_key = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $result[0], 'api_key');
101 return self
::error("This user does not have a valid API key in the database, and therefore cannot authenticate through this interface");
104 // Test to see if I can pull the data I need, since I know I have a good value.
105 $user = &CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', $api_key);
107 $session->set('api_key', $api_key);
108 $session->set('key', $result[2]);
109 $session->set('rest_time', time());
110 $session->set('PHPSESSID', session_id());
111 $session->set('cms_user_id', $result[1]);
113 return self
::simple(array('api_key' => $api_key, 'PHPSESSID' => session_id(), 'key' => sha1($result[2])));
116 // Generates values needed for error messages
117 static function error($message = 'Unknown Error') {
119 'error_message' => $message,
125 // Generates values needed for non-error responses.
126 static function simple($params) {
127 $values = array('is_error' => 0);
133 $result = self
::handle();
134 return self
::output($result);
137 static function output(&$result) {
139 if (is_scalar($result)) {
143 $result = self
::simple(array('result' => $result));
145 elseif (is_array($result)) {
146 if (CRM_Utils_Array
::isHierarchical($result)) {
149 elseif (!array_key_exists('is_error', $result)) {
150 $result['is_error'] = 0;
154 $result = self
::error('Could not interpret return values from function.');
157 if (CRM_Utils_Array
::value('json', $_REQUEST)) {
158 header('Content-Type: text/javascript');
159 $json = json_encode(array_merge($result));
160 if (CRM_Utils_Array
::value('debug', $_REQUEST)) {
161 return self
::jsonFormated($json);
167 if (isset($result['count'])) {
170 $count = ' count="' . $result['count'] . '" ';
175 $xml = "<?xml version=\"1.0\"?>
176 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
178 // check if this is a single element result (contact_get etc)
181 foreach ($result['values'] as $n => $v) {
182 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($v) . "</Result>\n";
186 $xml .= "<Result>\n" . CRM_Utils_Array
::xml($result) . "</Result>\n";
189 $xml .= "</ResultSet>\n";
193 static function jsonFormated($json) {
203 for ($i = 0; $i < strlen($json); $i++
) {
219 $result .= $char . $newline . str_repeat($tab, $tabcount);
229 $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
234 if ($inquote ||
$inarray) {
237 else $result .= $char . $newline . str_repeat($tab, $tabcount);
241 $inquote = !$inquote;
271 static function handle() {
272 // Get the function name being called from the q parameter in the query string
273 $q = CRM_Utils_array
::value('q', $_REQUEST);
274 // or for the rest interface, from fnName
275 $r = CRM_Utils_array
::value('fnName', $_REQUEST);
280 $args = explode('/', $q);
281 // If the function isn't in the civicrm namespace, reject the request.
282 if ($args[0] != 'civicrm') {
283 return self
::error('Unknown function invocation.');
286 // If the query string is malformed, reject the request.
287 if ((count($args) != 3) && ($args[1] != 'login') && ($args[1] != 'ping')) {
288 return self
::error('Unknown function invocation.');
291 if ($args[1] == 'login') {
292 $name = CRM_Utils_Request
::retrieve('name', 'String', $store, FALSE, NULL, 'REQUEST');
293 $pass = CRM_Utils_Request
::retrieve('pass', 'String', $store, FALSE, NULL, 'REQUEST');
297 return self
::error('Invalid name / password.');
299 return self
::authenticate($name, $pass);
301 elseif ($args[1] == 'ping') {
306 // or the new format (entity+action)
307 $args[1] = CRM_Utils_array
::value('entity', $_REQUEST);
308 $args[2] = CRM_Utils_array
::value('action', $_REQUEST);
310 // Everyone should be required to provide the server key, so the whole
311 // interface can be disabled in more change to the configuration file.
312 // This used to be done in the authenticate function, but that was bad...trust me
313 // first check for civicrm site key
314 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
315 $docLink = CRM_Utils_System
::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
316 $key = CRM_Utils_array
::value('key', $_REQUEST);
318 return self
::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
320 return self
::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
324 // At this point we know we are not calling either login or ping (neither of which
325 // require authentication prior to being called. Therefore, at this point we need
326 // to make sure we're working with a trusted user.
328 // There are two ways to check for a trusted user:
329 // First: they can be someone that has a valid session currently
330 // Second: they can be someone that has provided an API_Key
334 // Check for valid session. Session ID's only appear here if you have
335 // run the rest_api login function. That might be a problem for the
338 // XXX This is the old way of doing it. We're going to want to get rid of this
339 $session = CRM_Core_Session
::singleton();
340 if ($session->get('PHPSESSID')) {
344 // If the user does not have a valid session (most likely to be used by people using
345 // an ajax interface), we need to check to see if they are carring a valid user's
348 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
349 if (!$api_key ||
strtolower($api_key) == 'null') {
350 return self
::error("FATAL:mandatory param 'api_key' (user key) missing");
352 $valid_user = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
355 // If we didn't find a valid user either way, then die.
356 if (empty($valid_user)) {
357 // XXX correct error so only reflects api_key
358 return self
::error("Invalid session or user api_key invalid");
361 return self
::process($args);
364 static function process(&$args, $restInterface = TRUE) {
365 $params = &self
::buildParamList();
367 $params['check_permissions'] = TRUE;
368 $fnName = $apiFile = NULL;
369 // clean up all function / class names. they should be alphanumeric and _ only
370 for ($i = 1; $i <= 3; $i++
) {
371 if (!empty($args[$i])) {
372 $args[$i] = CRM_Utils_String
::munge($args[$i]);
376 // incase of ajax functions className is passed in url
377 if (isset($params['className'])) {
378 $params['className'] = CRM_Utils_String
::munge($params['className']);
380 // functions that are defined only in AJAX.php can be called via
382 if (!CRM_Core_Page_AJAX
::checkAuthz('method', $params['className'], $params['fnName'])) {
383 return self
::error('Unknown function invocation.');
386 return call_user_func(array($params['className'], $params['fnName']), $params);
389 if (!array_key_exists('version', $params)) {
390 $params['version'] = 3;
393 if ($params['version'] == 2) {
394 $result['is_error'] = 1;
395 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
396 $result['deprecated'] = "Please upgrade to API v3";
400 if ($_SERVER['REQUEST_METHOD'] == 'GET' && strtolower(substr( $args[2],0,3)) != 'get') {
401 // get only valid for non destructive methods
402 require_once 'api/v3/utils.php';
403 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
405 'IP' => $_SERVER['REMOTE_ADDR'],
406 'level' => 'security',
407 'referer' => $_SERVER['HTTP_REFERER'],
408 'reason' => 'Destructive HTTP GET',
413 // trap all fatal errors
414 CRM_Core_Error
::setCallback(array('CRM_Utils_REST', 'fatal'));
415 $result = civicrm_api($args[1], $args[2], $params);
416 CRM_Core_Error
::setCallback();
418 if ($result === FALSE) {
419 return self
::error('Unknown error.');
424 static function &buildParamList() {
436 if (array_key_exists('json', $_REQUEST) && $_REQUEST['json'][0] == "{") {
437 $params = json_decode($_REQUEST['json'], TRUE);
439 echo json_encode(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
440 CRM_Utils_System
::civiExit();
443 foreach ($_REQUEST as $n => $v) {
444 if (!array_key_exists($n, $skipVars)) {
448 if (array_key_exists('return', $_REQUEST) && is_array($_REQUEST['return'])) {
449 foreach ($_REQUEST['return'] as $key => $v) $params['return.' . $key] = 1;
454 static function fatal($pearError) {
455 header('Content-Type: text/xml');
457 $error['code'] = $pearError->getCode();
458 $error['error_message'] = $pearError->getMessage();
459 $error['mode'] = $pearError->getMode();
460 $error['debug_info'] = $pearError->getDebugInfo();
461 $error['type'] = $pearError->getType();
462 $error['user_info'] = $pearError->getUserInfo();
463 $error['to_string'] = $pearError->toString();
464 $error['is_error'] = 1;
466 echo self
::output($error);
468 CRM_Utils_System
::civiExit();
471 static function APIDoc() {
473 CRM_Utils_System
::setTitle("API Parameters");
474 $template = CRM_Core_Smarty
::singleton();
475 return CRM_Utils_System
::theme(
476 $template->fetch('CRM/Core/APIDoc.tpl')
480 static function ajaxDoc() {
481 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/api/explorer'));
484 /** used to load a template "inline", eg. for ajax, without having to build a menu for each template */
485 static function loadTemplate () {
486 $request = CRM_Utils_Request
::retrieve( 'q', 'String');
487 if (false !== strpos($request, '..')) {
488 die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
491 $request = split ('/',$request);
492 $entity = _civicrm_api_get_camel_name($request[2]);
493 $tplfile=_civicrm_api_get_camel_name($request[3]);
495 $tpl = 'CRM/'.$entity.'/Page/Inline/'.$tplfile.'.tpl';
496 $smarty= CRM_Core_Smarty
::singleton( );
497 CRM_Utils_System
::setTitle( "$entity::$tplfile inline $tpl" );
498 if( !$smarty->template_exists($tpl) ){
499 header("Status: 404 Not Found");
500 die ("Can't find the requested template file templates/$tpl");
502 if (array_key_exists('id',$_GET)) {// special treatmenent, because it's often used
503 $smarty->assign ('id',(int)$_GET['id']);// an id is always positive
505 $pos = strpos (implode (array_keys ($_GET)),'<') ;
507 if ($pos !== false) {
508 die ("SECURITY FATAL: one of the param names contains <");
510 $param = array_map( 'htmlentities' , $_GET);
512 $smarty->assign_by_ref("request", $param);
514 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
515 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
517 $smarty->assign( 'tplFile', $tpl );
518 $config = CRM_Core_Config
::singleton();
519 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework
) .'.tpl' );
521 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region
::instance('html-header', FALSE)) {
522 CRM_Utils_System
::addHTMLHead($region->render(''));
524 CRM_Utils_System
::appendTPLFile( $tpl, $content );
526 return CRM_Utils_System
::theme($content);
529 $content = "<!-- .tpl file embeded: $tpl -->\n";
530 CRM_Utils_System
::appendTPLFile( $tpl, $content );
531 echo $content . $smarty->fetch ($tpl);
532 CRM_Utils_System
::civiExit( );
536 /** This is a wrapper so you can call an api via json (it returns json too)
537 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals
538 * works for POST & GET (POST recommended)
540 static function ajaxJson() {
541 require_once 'api/v3/utils.php';
542 if (!$config->debug
&& (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
543 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
545 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
547 'IP' => $_SERVER['REMOTE_ADDR'],
548 'level' => 'security',
549 'referer' => $_SERVER['HTTP_REFERER'],
550 'reason' => 'CSRF suspected',
553 echo json_encode($error);
554 CRM_Utils_System
::civiExit();
556 if (empty($_REQUEST['entity'])) {
557 echo json_encode(civicrm_api3_create_error('missing entity param'));
558 CRM_Utils_System
::civiExit();
560 if (empty($_REQUEST['entity'])) {
561 echo json_encode(civicrm_api3_create_error('missing entity entity'));
562 CRM_Utils_System
::civiExit();
564 if (!empty($_REQUEST['json'])) {
565 $params = json_decode($_REQUEST['json'], TRUE);
567 $entity = CRM_Utils_String
::munge(CRM_Utils_Array
::value('entity', $_REQUEST));
568 $action = CRM_Utils_String
::munge(CRM_Utils_Array
::value('action', $_REQUEST));
569 if (!is_array($params)) {
570 echo json_encode(array('is_error' => 1, 'error_message', 'invalid json format: ?{"param_with_double_quote":"value"}'));
571 CRM_Utils_System
::civiExit();
574 $params['check_permissions'] = TRUE;
575 $params['version'] = 3;
576 $_REQUEST['json'] = 1;
577 if (!$params['sequential']) {
578 $params['sequential'] = 1;
580 // trap all fatal errors
581 CRM_Core_Error
::setCallback(array('CRM_Utils_REST', 'fatal'));
582 $result = civicrm_api($entity, $action, $params);
584 CRM_Core_Error
::setCallback();
586 echo self
::output($result);
588 CRM_Utils_System
::civiExit();
591 static function ajax() {
592 // this is driven by the menu system, so we can use permissioning to
593 // restrict calls to this etc
594 // the request has to be sent by an ajax call. First line of protection against csrf
595 $config = CRM_Core_Config
::singleton();
596 if (!$config->debug
&&
597 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
598 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
601 require_once 'api/v3/utils.php';
602 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
604 'IP' => $_SERVER['REMOTE_ADDR'],
605 'level' => 'security',
606 'referer' => $_SERVER['HTTP_REFERER'],
607 'reason' => 'CSRF suspected',
610 echo json_encode($error);
611 CRM_Utils_System
::civiExit();
614 $q = CRM_Utils_Array
::value('fnName', $_REQUEST);
616 $entity = CRM_Utils_Array
::value('entity', $_REQUEST);
617 $action = CRM_Utils_Array
::value('action', $_REQUEST);
618 if (!$entity ||
!$action) {
619 $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
620 echo self
::output($err);
621 CRM_Utils_System
::civiExit();
623 $args = array('civicrm', $entity, $action);
626 $args = explode('/', $q);
629 // get the class name, since all ajax functions pass className
630 $className = CRM_Utils_Array
::value('className', $_REQUEST);
632 // If the function isn't in the civicrm namespace, reject the request.
633 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
634 return self
::error('Unknown function invocation.');
637 $result = self
::process($args, FALSE);
639 echo self
::output($result);
641 CRM_Utils_System
::civiExit();
644 function loadCMSBootstrap() {
645 $q = CRM_Utils_array
::value('q', $_REQUEST);
646 $args = explode('/', $q);
648 // If the function isn't in the civicrm namespace or request
649 // is for login or ping
650 if (empty($args) ||
$args[0] != 'civicrm' ||
651 ((count($args) != 3) && ($args[1] != 'login') && ($args[1] != 'ping')) ||
657 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
661 if ($args[1] == 'login') {
662 CRM_Utils_System
::loadBootStrap(CRM_Core_DAO
::$_nullArray, TRUE, FALSE);
667 $session = CRM_Core_Session
::singleton();
669 if ($session->get('PHPSESSID') && $session->get('cms_user_id')) {
670 $uid = $session->get('cms_user_id');
675 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
676 $contact_id = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
678 $uid = CRM_Core_BAO_UFMatch
::getUFId($contact_id);
683 CRM_Utils_System
::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
686 $err = array('error_message' => 'no CMS user associated with given api-key', 'is_error' => 1);
687 echo self
::output($err);
688 CRM_Utils_System
::civiExit();