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 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
337 $session = CRM_Core_Session
::singleton();
338 if ($session->get('PHPSESSID')) {
342 // If the user does not have a valid session (most likely to be used by people using
343 // an ajax interface), we need to check to see if they are carring a valid user's
346 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
347 if (!$api_key ||
strtolower($api_key) == 'null') {
348 return ("FATAL:mandatory param 'api_key' (user key) missing");
350 $valid_user = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
353 // If we didn't find a valid user either way, then die.
354 if (empty($valid_user)) {
355 return self
::error("Invalid session or user api_key invalid");
358 return self
::process($args);
361 static function process(&$args, $restInterface = TRUE) {
362 $params = &self
::buildParamList();
364 $params['check_permissions'] = TRUE;
365 $fnName = $apiFile = NULL;
366 // clean up all function / class names. they should be alphanumeric and _ only
367 for ($i = 1; $i <= 3; $i++
) {
368 if (!empty($args[$i])) {
369 $args[$i] = CRM_Utils_String
::munge($args[$i]);
373 // incase of ajax functions className is passed in url
374 if (isset($params['className'])) {
375 $params['className'] = CRM_Utils_String
::munge($params['className']);
377 // functions that are defined only in AJAX.php can be called via
379 if (!CRM_Core_Page_AJAX
::checkAuthz('method', $params['className'], $params['fnName'])) {
380 return self
::error('Unknown function invocation.');
383 return call_user_func(array($params['className'], $params['fnName']), $params);
386 if (!array_key_exists('version', $params)) {
387 $params['version'] = 3;
390 if ($params['version'] == 2) {
391 $result['is_error'] = 1;
392 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
393 $result['deprecated'] = "Please upgrade to API v3";
397 if ($_SERVER['REQUEST_METHOD'] == 'GET' && strtolower(substr( $args[2],0,3)) != 'get') {
398 // get only valid for non destructive methods
399 require_once 'api/v3/utils.php';
400 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
402 'IP' => $_SERVER['REMOTE_ADDR'],
403 'level' => 'security',
404 'referer' => $_SERVER['HTTP_REFERER'],
405 'reason' => 'Destructive HTTP GET',
410 // trap all fatal errors
411 CRM_Core_Error
::setCallback(array('CRM_Utils_REST', 'fatal'));
412 $result = civicrm_api($args[1], $args[2], $params);
413 CRM_Core_Error
::setCallback();
415 if ($result === FALSE) {
416 return self
::error('Unknown error.');
421 static function &buildParamList() {
433 if (array_key_exists('json', $_REQUEST) && $_REQUEST['json'][0] == "{") {
434 $params = json_decode($_REQUEST['json'], TRUE);
436 echo json_encode(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
437 CRM_Utils_System
::civiExit();
440 foreach ($_REQUEST as $n => $v) {
441 if (!array_key_exists($n, $skipVars)) {
445 if (array_key_exists('return', $_REQUEST) && is_array($_REQUEST['return'])) {
446 foreach ($_REQUEST['return'] as $key => $v) $params['return.' . $key] = 1;
451 static function fatal($pearError) {
452 header('Content-Type: text/xml');
454 $error['code'] = $pearError->getCode();
455 $error['error_message'] = $pearError->getMessage();
456 $error['mode'] = $pearError->getMode();
457 $error['debug_info'] = $pearError->getDebugInfo();
458 $error['type'] = $pearError->getType();
459 $error['user_info'] = $pearError->getUserInfo();
460 $error['to_string'] = $pearError->toString();
461 $error['is_error'] = 1;
463 echo self
::output($error);
465 CRM_Utils_System
::civiExit();
468 static function APIDoc() {
470 CRM_Utils_System
::setTitle("API Parameters");
471 $template = CRM_Core_Smarty
::singleton();
472 return CRM_Utils_System
::theme(
473 $template->fetch('CRM/Core/APIDoc.tpl')
477 static function ajaxDoc() {
478 return CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/api/explorer'));
481 /** used to load a template "inline", eg. for ajax, without having to build a menu for each template */
482 static function loadTemplate () {
483 $request = CRM_Utils_Request
::retrieve( 'q', 'String');
484 if (false !== strpos($request, '..')) {
485 die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
488 $request = split ('/',$request);
489 $entity = _civicrm_api_get_camel_name($request[2]);
490 $tplfile=_civicrm_api_get_camel_name($request[3]);
492 $tpl = 'CRM/'.$entity.'/Page/Inline/'.$tplfile.'.tpl';
493 $smarty= CRM_Core_Smarty
::singleton( );
494 CRM_Utils_System
::setTitle( "$entity::$tplfile inline $tpl" );
495 if( !$smarty->template_exists($tpl) ){
496 header("Status: 404 Not Found");
497 die ("Can't find the requested template file templates/$tpl");
499 if (array_key_exists('id',$_GET)) {// special treatmenent, because it's often used
500 $smarty->assign ('id',(int)$_GET['id']);// an id is always positive
502 $pos = strpos (implode (array_keys ($_GET)),'<') ;
504 if ($pos !== false) {
505 die ("SECURITY FATAL: one of the param names contains <");
507 $param = array_map( 'htmlentities' , $_GET);
509 $smarty->assign_by_ref("request", $param);
511 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
512 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
514 $smarty->assign( 'tplFile', $tpl );
515 $config = CRM_Core_Config
::singleton();
516 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework
) .'.tpl' );
518 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region
::instance('html-header', FALSE)) {
519 CRM_Utils_System
::addHTMLHead($region->render(''));
521 CRM_Utils_System
::appendTPLFile( $tpl, $content );
523 return CRM_Utils_System
::theme($content);
526 $content = "<!-- .tpl file embeded: $tpl -->\n";
527 CRM_Utils_System
::appendTPLFile( $tpl, $content );
528 echo $content . $smarty->fetch ($tpl);
529 CRM_Utils_System
::civiExit( );
533 /** This is a wrapper so you can call an api via json (it returns json too)
534 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals
535 * works for POST & GET (POST recommended)
537 static function ajaxJson() {
538 require_once 'api/v3/utils.php';
539 if (!$config->debug
&&
540 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
541 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
544 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
546 'IP' => $_SERVER['REMOTE_ADDR'],
547 'level' => 'security',
548 'referer' => $_SERVER['HTTP_REFERER'],
549 'reason' => 'CSRF suspected',
552 echo json_encode($error);
553 CRM_Utils_System
::civiExit();
555 if (empty($_REQUEST['entity'])) {
556 echo json_encode(civicrm_api3_create_error('missing entity param'));
557 CRM_Utils_System
::civiExit();
559 if (empty($_REQUEST['entity'])) {
560 echo json_encode(civicrm_api3_create_error('missing entity entity'));
561 CRM_Utils_System
::civiExit();
563 if (!empty($_REQUEST['json'])) {
564 $params = json_decode($_REQUEST['json'], TRUE);
566 $entity = CRM_Utils_String
::munge(CRM_Utils_Array
::value('entity', $_REQUEST));
567 $action = CRM_Utils_String
::munge(CRM_Utils_Array
::value('action', $_REQUEST));
568 if (!is_array($params)) {
569 echo json_encode(array('is_error' => 1, 'error_message', 'invalid json format: ?{"param_with_double_quote":"value"}'));
570 CRM_Utils_System
::civiExit();
573 $params['check_permissions'] = TRUE;
574 $params['version'] = 3;
575 $_REQUEST['json'] = 1;
576 if (!$params['sequential']) {
577 $params['sequential'] = 1;
579 // trap all fatal errors
580 CRM_Core_Error
::setCallback(array('CRM_Utils_REST', 'fatal'));
581 $result = civicrm_api($entity, $action, $params);
583 CRM_Core_Error
::setCallback();
585 echo self
::output($result);
587 CRM_Utils_System
::civiExit();
590 static function ajax() {
591 // this is driven by the menu system, so we can use permissioning to
592 // restrict calls to this etc
593 // the request has to be sent by an ajax call. First line of protection against csrf
594 $config = CRM_Core_Config
::singleton();
595 if (0 && !$config->debug
&&
596 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
597 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
600 require_once 'api/v3/utils.php';
601 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
603 'IP' => $_SERVER['REMOTE_ADDR'],
604 'level' => 'security',
605 'referer' => $_SERVER['HTTP_REFERER'],
606 'reason' => 'CSRF suspected',
609 echo json_encode($error);
610 CRM_Utils_System
::civiExit();
613 $q = CRM_Utils_Array
::value('fnName', $_REQUEST);
615 $entity = CRM_Utils_Array
::value('entity', $_REQUEST);
616 $action = CRM_Utils_Array
::value('action', $_REQUEST);
617 if (!$entity ||
!$action) {
618 $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
619 echo self
::output($err);
620 CRM_Utils_System
::civiExit();
622 $args = array('civicrm', $entity, $action);
625 $args = explode('/', $q);
628 // get the class name, since all ajax functions pass className
629 $className = CRM_Utils_Array
::value('className', $_REQUEST);
631 // If the function isn't in the civicrm namespace, reject the request.
632 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
633 return self
::error('Unknown function invocation.');
636 $result = self
::process($args, FALSE);
638 echo self
::output($result);
640 CRM_Utils_System
::civiExit();
643 function loadCMSBootstrap() {
644 $q = CRM_Utils_array
::value('q', $_REQUEST);
645 $args = explode('/', $q);
647 // If no 'q' parameter is provided, try to populate args
648 // with entity and action (API v3)
649 if ( empty($args) ||
$args[0] == '' ) {
650 $entity = CRM_Utils_array
::value( 'entity', $_REQUEST );
651 $action = CRM_Utils_array
::value( 'action', $_REQUEST );
652 if (($entity !== null) && ($action !== null)) {
653 $args[0] = 'civicrm';
659 // If the function isn't in the civicrm namespace or request
660 // is for login or ping
661 if (empty($args) ||
$args[0] != 'civicrm' ||
662 ((count($args) != 3) && ($args[1] != 'login') && ($args[1] != 'ping')) ||
668 if (!CRM_Utils_System
::authenticateKey(FALSE)) {
672 if ($args[1] == 'login') {
673 CRM_Utils_System
::loadBootStrap(CRM_Core_DAO
::$_nullArray, TRUE, FALSE);
678 $session = CRM_Core_Session
::singleton();
680 if ($session->get('PHPSESSID') && $session->get('cms_user_id')) {
681 $uid = $session->get('cms_user_id');
686 $api_key = CRM_Utils_Request
::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
687 $contact_id = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
689 $uid = CRM_Core_BAO_UFMatch
::getUFId($contact_id);
694 CRM_Utils_System
::loadBootStrap(array('uid' => $uid), TRUE, FALSE);