Adding comments, playing with REST
[civicrm-core.git] / CRM / Utils / REST.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This class handles all REST client requests.
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2013
33 *
34 */
35 class CRM_Utils_REST {
36
37 /**
38 * Number of seconds we should let a REST process idle
39 * @static
40 */
41 static $rest_timeout = 0;
42
43 /**
44 * Cache the actual UF Class
45 */
46 public $ufClass;
47
48 /**
49 * Class constructor. This caches the real user framework class locally,
50 * so we can use it for authentication and validation.
51 *
52 * @param string $uf The userframework class
53 */
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);
59 }
60
61 /**
62 * Simple ping function to test for liveness.
63 *
64 * @param string $var The string to be echoed
65 *
66 * @return string $var
67 * @access public
68 */
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"));
74 }
75
76 /**
77 * Authentication wrapper to the UF Class
78 *
79 * @param string $name Login name
80 * @param string $pass Password
81 *
82 * @return string The REST Client key
83 * @access public
84 * @static
85 */
86 public static function authenticate($name, $pass) {
87
88 $result = CRM_Utils_System::authenticate($name, $pass);
89
90 if (empty($result)) {
91 return self::error('Could not authenticate user, invalid name or password.');
92 }
93
94 $session = CRM_Core_Session::singleton();
95 $api_key = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $result[0], 'api_key');
96
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");
102 }
103
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);
106
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]);
112
113 return self::simple(array('api_key' => $api_key, 'PHPSESSID' => session_id(), 'key' => sha1($result[2])));
114 }
115
116 // Generates values needed for error messages
117 static function error($message = 'Unknown Error') {
118 $values = array(
119 'error_message' => $message,
120 'is_error' => 1,
121 );
122 return $values;
123 }
124
125 // Generates values needed for non-error responses.
126 static function simple($params) {
127 $values = array('is_error' => 0);
128 $values += $params;
129 return $values;
130 }
131
132 function run() {
133 $result = self::handle();
134 return self::output($result);
135 }
136
137 static function output(&$result) {
138 $hier = FALSE;
139 if (is_scalar($result)) {
140 if (!$result) {
141 $result = 0;
142 }
143 $result = self::simple(array('result' => $result));
144 }
145 elseif (is_array($result)) {
146 if (CRM_Utils_Array::isHierarchical($result)) {
147 $hier = TRUE;
148 }
149 elseif (!array_key_exists('is_error', $result)) {
150 $result['is_error'] = 0;
151 }
152 }
153 else {
154 $result = self::error('Could not interpret return values from function.');
155 }
156
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);
162 }
163 return $json;
164 }
165
166
167 if (isset($result['count'])) {
168
169
170 $count = ' count="' . $result['count'] . '" ';
171
172
173 }
174 else $count = "";
175 $xml = "<?xml version=\"1.0\"?>
176 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
177 ";
178 // check if this is a single element result (contact_get etc)
179 // or multi element
180 if ($hier) {
181 foreach ($result['values'] as $n => $v) {
182 $xml .= "<Result>\n" . CRM_Utils_Array::xml($v) . "</Result>\n";
183 }
184 }
185 else {
186 $xml .= "<Result>\n" . CRM_Utils_Array::xml($result) . "</Result>\n";
187 }
188
189 $xml .= "</ResultSet>\n";
190 return $xml;
191 }
192
193 static function jsonFormated($json) {
194 $tabcount = 0;
195 $result = '';
196 $inquote = FALSE;
197 $inarray = FALSE;
198 $ignorenext = FALSE;
199
200 $tab = "\t";
201 $newline = "\n";
202
203 for ($i = 0; $i < strlen($json); $i++) {
204 $char = $json[$i];
205
206 if ($ignorenext) {
207 $result .= $char;
208 $ignorenext = FALSE;
209 }
210 else {
211 switch ($char) {
212 case '{':
213 if ($inquote) {
214 $result .= $char;
215 }
216 else {
217 $inarray = FALSE;
218 $tabcount++;
219 $result .= $char . $newline . str_repeat($tab, $tabcount);
220 }
221 break;
222
223 case '}':
224 if ($inquote) {
225 $result .= $char;
226 }
227 else {
228 $tabcount--;
229 $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
230 }
231 break;
232
233 case ',':
234 if ($inquote || $inarray) {
235 $result .= $char;
236 }
237 else $result .= $char . $newline . str_repeat($tab, $tabcount);
238 break;
239
240 case '"':
241 $inquote = !$inquote;
242 $result .= $char;
243 break;
244
245 case '\\':
246 if ($inquote) {
247 $ignorenext = TRUE;
248 }
249 $result .= $char;
250 break;
251
252 case '[':
253 $inarray = TRUE;
254 $result .= $char;
255 break;
256
257 case ']':
258 $inarray = FALSE;
259 $result .= $char;
260 break;
261
262 default:
263 $result .= $char;
264 }
265 }
266 }
267
268 return $result;
269 }
270
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);
276 if (!empty($r)) {
277 $q = $r;
278 }
279 if (!empty($q)) {
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.');
284 }
285
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.');
289 }
290 $store = NULL;
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');
294 if (empty($name) ||
295 empty($pass)
296 ) {
297 return self::error('Invalid name / password.');
298 }
299 return self::authenticate($name, $pass);
300 }
301 elseif ($args[1] == 'ping') {
302 return self::ping();
303 }
304 }
305 else {
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);
309 }
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);
317 if (empty($key)) {
318 return self::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
319 }
320 return self::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
321 }
322
323
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.
327
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
331
332 $valid_user = FALSE;
333
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
336 // AJAX methods.
337
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')) {
341 $valid_user = TRUE;
342 }
343
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
346 // secret key.
347 if (!$valid_user) {
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");
351 }
352 $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
353 }
354
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");
359 }
360
361 return self::process($args);
362 }
363
364 static function process(&$args, $restInterface = TRUE) {
365 $params = &self::buildParamList();
366
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]);
373 }
374 }
375
376 // incase of ajax functions className is passed in url
377 if (isset($params['className'])) {
378 $params['className'] = CRM_Utils_String::munge($params['className']);
379
380 // functions that are defined only in AJAX.php can be called via
381 // rest interface
382 if (!CRM_Core_Page_AJAX::checkAuthz('method', $params['className'], $params['fnName'])) {
383 return self::error('Unknown function invocation.');
384 }
385
386 return call_user_func(array($params['className'], $params['fnName']), $params);
387 }
388
389 if (!array_key_exists('version', $params)) {
390 $params['version'] = 3;
391 }
392
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";
397 return $result;
398 }
399
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.",
404 array(
405 'IP' => $_SERVER['REMOTE_ADDR'],
406 'level' => 'security',
407 'referer' => $_SERVER['HTTP_REFERER'],
408 'reason' => 'Destructive HTTP GET',
409 )
410 );
411 }
412
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();
417
418 if ($result === FALSE) {
419 return self::error('Unknown error.');
420 }
421 return $result;
422 }
423
424 static function &buildParamList() {
425 $params = array();
426
427 $skipVars = array(
428 'q' => 1,
429 'json' => 1,
430 'key' => 1,
431 'api_key' => 1,
432 'entity' => 1,
433 'action' => 1,
434 );
435
436 if (array_key_exists('json', $_REQUEST) && $_REQUEST['json'][0] == "{") {
437 $params = json_decode($_REQUEST['json'], TRUE);
438 if(empty($params)) {
439 echo json_encode(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
440 CRM_Utils_System::civiExit();
441 }
442 }
443 foreach ($_REQUEST as $n => $v) {
444 if (!array_key_exists($n, $skipVars)) {
445 $params[$n] = $v;
446 }
447 }
448 if (array_key_exists('return', $_REQUEST) && is_array($_REQUEST['return'])) {
449 foreach ($_REQUEST['return'] as $key => $v) $params['return.' . $key] = 1;
450 }
451 return $params;
452 }
453
454 static function fatal($pearError) {
455 header('Content-Type: text/xml');
456 $error = array();
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;
465
466 echo self::output($error);
467
468 CRM_Utils_System::civiExit();
469 }
470
471 static function APIDoc() {
472
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')
477 );
478 }
479
480 static function ajaxDoc() {
481 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/api/explorer'));
482 }
483
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");
489 }
490
491 $request = split ('/',$request);
492 $entity = _civicrm_api_get_camel_name($request[2]);
493 $tplfile=_civicrm_api_get_camel_name($request[3]);
494
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");
501 }
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
504 }
505 $pos = strpos (implode (array_keys ($_GET)),'<') ;
506
507 if ($pos !== false) {
508 die ("SECURITY FATAL: one of the param names contains &lt;");
509 }
510 $param = array_map( 'htmlentities' , $_GET);
511 unset($param['q']);
512 $smarty->assign_by_ref("request", $param);
513
514 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
515 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
516
517 $smarty->assign( 'tplFile', $tpl );
518 $config = CRM_Core_Config::singleton();
519 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework) .'.tpl' );
520
521 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) {
522 CRM_Utils_System::addHTMLHead($region->render(''));
523 }
524 CRM_Utils_System::appendTPLFile( $tpl, $content );
525
526 return CRM_Utils_System::theme($content);
527
528 } else {
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( );
533 }
534 }
535
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)
539 **/
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"
544 )) {
545 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
546 array(
547 'IP' => $_SERVER['REMOTE_ADDR'],
548 'level' => 'security',
549 'referer' => $_SERVER['HTTP_REFERER'],
550 'reason' => 'CSRF suspected',
551 )
552 );
553 echo json_encode($error);
554 CRM_Utils_System::civiExit();
555 }
556 if (empty($_REQUEST['entity'])) {
557 echo json_encode(civicrm_api3_create_error('missing entity param'));
558 CRM_Utils_System::civiExit();
559 }
560 if (empty($_REQUEST['entity'])) {
561 echo json_encode(civicrm_api3_create_error('missing entity entity'));
562 CRM_Utils_System::civiExit();
563 }
564 if (!empty($_REQUEST['json'])) {
565 $params = json_decode($_REQUEST['json'], TRUE);
566 }
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();
572 }
573
574 $params['check_permissions'] = TRUE;
575 $params['version'] = 3;
576 $_REQUEST['json'] = 1;
577 if (!$params['sequential']) {
578 $params['sequential'] = 1;
579 }
580 // trap all fatal errors
581 CRM_Core_Error::setCallback(array('CRM_Utils_REST', 'fatal'));
582 $result = civicrm_api($entity, $action, $params);
583
584 CRM_Core_Error::setCallback();
585
586 echo self::output($result);
587
588 CRM_Utils_System::civiExit();
589 }
590
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"
599 )
600 ) {
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().",
603 array(
604 'IP' => $_SERVER['REMOTE_ADDR'],
605 'level' => 'security',
606 'referer' => $_SERVER['HTTP_REFERER'],
607 'reason' => 'CSRF suspected',
608 )
609 );
610 echo json_encode($error);
611 CRM_Utils_System::civiExit();
612 }
613
614 $q = CRM_Utils_Array::value('fnName', $_REQUEST);
615 if (!$q) {
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();
622 }
623 $args = array('civicrm', $entity, $action);
624 }
625 else {
626 $args = explode('/', $q);
627 }
628
629 // get the class name, since all ajax functions pass className
630 $className = CRM_Utils_Array::value('className', $_REQUEST);
631
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.');
635 }
636
637 $result = self::process($args, FALSE);
638
639 echo self::output($result);
640
641 CRM_Utils_System::civiExit();
642 }
643
644 function loadCMSBootstrap() {
645 $q = CRM_Utils_array::value('q', $_REQUEST);
646 $args = explode('/', $q);
647
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')) ||
652 $args[1] == 'ping'
653 ) {
654 return;
655 }
656
657 if (!CRM_Utils_System::authenticateKey(FALSE)) {
658 return;
659 }
660
661 if ($args[1] == 'login') {
662 CRM_Utils_System::loadBootStrap(CRM_Core_DAO::$_nullArray, TRUE, FALSE);
663 return;
664 }
665
666 $uid = NULL;
667 $session = CRM_Core_Session::singleton();
668
669 if ($session->get('PHPSESSID') && $session->get('cms_user_id')) {
670 $uid = $session->get('cms_user_id');
671 }
672
673 if (!$uid) {
674 $store = NULL;
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');
677 if ($contact_id) {
678 $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
679 }
680 }
681
682 if ($uid) {
683 CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
684 }
685 else {
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();
689 }
690 }
691 }
692