Merge pull request #727 from dlobo/MiscFixes
[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 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 $session = CRM_Core_Session::singleton();
338 if ($session->get('PHPSESSID')) {
339 $valid_user = TRUE;
340 }
341
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
344 // secret key.
345 if (!$valid_user) {
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");
349 }
350 $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
351 }
352
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");
356 }
357
358 return self::process($args);
359 }
360
361 static function process(&$args, $restInterface = TRUE) {
362 $params = &self::buildParamList();
363
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]);
370 }
371 }
372
373 // incase of ajax functions className is passed in url
374 if (isset($params['className'])) {
375 $params['className'] = CRM_Utils_String::munge($params['className']);
376
377 // functions that are defined only in AJAX.php can be called via
378 // rest interface
379 if (!CRM_Core_Page_AJAX::checkAuthz('method', $params['className'], $params['fnName'])) {
380 return self::error('Unknown function invocation.');
381 }
382
383 return call_user_func(array($params['className'], $params['fnName']), $params);
384 }
385
386 if (!array_key_exists('version', $params)) {
387 $params['version'] = 3;
388 }
389
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";
394 return $result;
395 }
396
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.",
401 array(
402 'IP' => $_SERVER['REMOTE_ADDR'],
403 'level' => 'security',
404 'referer' => $_SERVER['HTTP_REFERER'],
405 'reason' => 'Destructive HTTP GET',
406 )
407 );
408 }
409
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();
414
415 if ($result === FALSE) {
416 return self::error('Unknown error.');
417 }
418 return $result;
419 }
420
421 static function &buildParamList() {
422 $params = array();
423
424 $skipVars = array(
425 'q' => 1,
426 'json' => 1,
427 'key' => 1,
428 'api_key' => 1,
429 'entity' => 1,
430 'action' => 1,
431 );
432
433 if (array_key_exists('json', $_REQUEST) && $_REQUEST['json'][0] == "{") {
434 $params = json_decode($_REQUEST['json'], TRUE);
435 if(empty($params)) {
436 echo json_encode(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
437 CRM_Utils_System::civiExit();
438 }
439 }
440 foreach ($_REQUEST as $n => $v) {
441 if (!array_key_exists($n, $skipVars)) {
442 $params[$n] = $v;
443 }
444 }
445 if (array_key_exists('return', $_REQUEST) && is_array($_REQUEST['return'])) {
446 foreach ($_REQUEST['return'] as $key => $v) $params['return.' . $key] = 1;
447 }
448 return $params;
449 }
450
451 static function fatal($pearError) {
452 header('Content-Type: text/xml');
453 $error = array();
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;
462
463 echo self::output($error);
464
465 CRM_Utils_System::civiExit();
466 }
467
468 static function APIDoc() {
469
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')
474 );
475 }
476
477 static function ajaxDoc() {
478 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/api/explorer'));
479 }
480
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");
486 }
487
488 $request = split ('/',$request);
489 $entity = _civicrm_api_get_camel_name($request[2]);
490 $tplfile=_civicrm_api_get_camel_name($request[3]);
491
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");
498 }
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
501 }
502 $pos = strpos (implode (array_keys ($_GET)),'<') ;
503
504 if ($pos !== false) {
505 die ("SECURITY FATAL: one of the param names contains &lt;");
506 }
507 $param = array_map( 'htmlentities' , $_GET);
508 unset($param['q']);
509 $smarty->assign_by_ref("request", $param);
510
511 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
512 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
513
514 $smarty->assign( 'tplFile', $tpl );
515 $config = CRM_Core_Config::singleton();
516 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework) .'.tpl' );
517
518 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) {
519 CRM_Utils_System::addHTMLHead($region->render(''));
520 }
521 CRM_Utils_System::appendTPLFile( $tpl, $content );
522
523 return CRM_Utils_System::theme($content);
524
525 } else {
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( );
530 }
531 }
532
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)
536 **/
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"
542 )
543 ) {
544 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api().",
545 array(
546 'IP' => $_SERVER['REMOTE_ADDR'],
547 'level' => 'security',
548 'referer' => $_SERVER['HTTP_REFERER'],
549 'reason' => 'CSRF suspected',
550 )
551 );
552 echo json_encode($error);
553 CRM_Utils_System::civiExit();
554 }
555 if (empty($_REQUEST['entity'])) {
556 echo json_encode(civicrm_api3_create_error('missing entity param'));
557 CRM_Utils_System::civiExit();
558 }
559 if (empty($_REQUEST['entity'])) {
560 echo json_encode(civicrm_api3_create_error('missing entity entity'));
561 CRM_Utils_System::civiExit();
562 }
563 if (!empty($_REQUEST['json'])) {
564 $params = json_decode($_REQUEST['json'], TRUE);
565 }
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();
571 }
572
573 $params['check_permissions'] = TRUE;
574 $params['version'] = 3;
575 $_REQUEST['json'] = 1;
576 if (!$params['sequential']) {
577 $params['sequential'] = 1;
578 }
579 // trap all fatal errors
580 CRM_Core_Error::setCallback(array('CRM_Utils_REST', 'fatal'));
581 $result = civicrm_api($entity, $action, $params);
582
583 CRM_Core_Error::setCallback();
584
585 echo self::output($result);
586
587 CRM_Utils_System::civiExit();
588 }
589
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"
598 )
599 ) {
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().",
602 array(
603 'IP' => $_SERVER['REMOTE_ADDR'],
604 'level' => 'security',
605 'referer' => $_SERVER['HTTP_REFERER'],
606 'reason' => 'CSRF suspected',
607 )
608 );
609 echo json_encode($error);
610 CRM_Utils_System::civiExit();
611 }
612
613 $q = CRM_Utils_Array::value('fnName', $_REQUEST);
614 if (!$q) {
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();
621 }
622 $args = array('civicrm', $entity, $action);
623 }
624 else {
625 $args = explode('/', $q);
626 }
627
628 // get the class name, since all ajax functions pass className
629 $className = CRM_Utils_Array::value('className', $_REQUEST);
630
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.');
634 }
635
636 $result = self::process($args, FALSE);
637
638 echo self::output($result);
639
640 CRM_Utils_System::civiExit();
641 }
642
643 function loadCMSBootstrap() {
644 $q = CRM_Utils_array::value('q', $_REQUEST);
645 $args = explode('/', $q);
646
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';
654 $args[1] = $entity;
655 $args[2] = $action;
656 }
657 }
658
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')) ||
663 $args[1] == 'ping'
664 ) {
665 return;
666 }
667
668 if (!CRM_Utils_System::authenticateKey(FALSE)) {
669 return;
670 }
671
672 if ($args[1] == 'login') {
673 CRM_Utils_System::loadBootStrap(CRM_Core_DAO::$_nullArray, TRUE, FALSE);
674 return;
675 }
676
677 $uid = NULL;
678 $session = CRM_Core_Session::singleton();
679
680 if ($session->get('PHPSESSID') && $session->get('cms_user_id')) {
681 $uid = $session->get('cms_user_id');
682 }
683
684 if (!$uid) {
685 $store = NULL;
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');
688 if ($contact_id) {
689 $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
690 }
691 }
692
693 if ($uid) {
694 CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
695 }
696 }
697 }
698