INFRA-132 - CRM/Utils - Convert single-line @param to multi-line
[civicrm-core.git] / CRM / Utils / REST.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * @internal 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
65 * The string to be echoed.
66 *
67 * @return string $var
68 */
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"));
74 }
75
76 // Generates values needed for error messages
77 /**
78 * @param string $message
79 *
80 * @return array
81 */
82 public static function error($message = 'Unknown Error') {
83 $values = array(
84 'error_message' => $message,
85 'is_error' => 1,
86 );
87 return $values;
88 }
89
90 // Generates values needed for non-error responses.
91 /**
92 * @param array $params
93 *
94 * @return array
95 */
96 public static function simple($params) {
97 $values = array('is_error' => 0);
98 $values += $params;
99 return $values;
100 }
101
102 /**
103 * @return string
104 */
105 public function run() {
106 $result = self::handle();
107 return self::output($result);
108 }
109
110 /**
111 * @return string
112 */
113 public function bootAndRun() {
114 $response = $this->loadCMSBootstrap();
115 if (is_array($response)) {
116 return self::output($response);
117 }
118 return $this->run();
119 }
120
121 /**
122 * @param $result
123 *
124 * @return string
125 */
126 public static function output(&$result) {
127 $requestParams = CRM_Utils_Request::exportValues();
128
129 $hier = FALSE;
130 if (is_scalar($result)) {
131 if (!$result) {
132 $result = 0;
133 }
134 $result = self::simple(array('result' => $result));
135 }
136 elseif (is_array($result)) {
137 if (CRM_Utils_Array::isHierarchical($result)) {
138 $hier = TRUE;
139 }
140 elseif (!array_key_exists('is_error', $result)) {
141 $result['is_error'] = 0;
142 }
143 }
144 else {
145 $result = self::error('Could not interpret return values from function.');
146 }
147
148 if (!empty($requestParams['json'])) {
149 header('Content-Type: application/json');
150 $json = json_encode(array_merge($result));
151 if (!empty($requestParams['prettyprint'])) {
152 // Used by the api explorer
153 return self::jsonFormated($json);
154 }
155 return $json;
156 }
157
158
159 if (isset($result['count'])) {
160 $count = ' count="' . $result['count'] . '" ';
161 }
162 else $count = "";
163 $xml = "<?xml version=\"1.0\"?>
164 <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count>
165 ";
166 // check if this is a single element result (contact_get etc)
167 // or multi element
168 if ($hier) {
169 foreach ($result['values'] as $n => $v) {
170 $xml .= "<Result>\n" . CRM_Utils_Array::xml($v) . "</Result>\n";
171 }
172 }
173 else {
174 $xml .= "<Result>\n" . CRM_Utils_Array::xml($result) . "</Result>\n";
175 }
176
177 $xml .= "</ResultSet>\n";
178 return $xml;
179 }
180
181 /**
182 * @param $json
183 *
184 * @return string
185 */
186 public static function jsonFormated($json) {
187 $tabcount = 0;
188 $result = '';
189 $inquote = FALSE;
190 $inarray = FALSE;
191 $ignorenext = FALSE;
192
193 $tab = "\t";
194 $newline = "\n";
195
196 for ($i = 0; $i < strlen($json); $i++) {
197 $char = $json[$i];
198
199 if ($ignorenext) {
200 $result .= $char;
201 $ignorenext = FALSE;
202 }
203 else {
204 switch ($char) {
205 case '{':
206 if ($inquote) {
207 $result .= $char;
208 }
209 else {
210 $inarray = FALSE;
211 $tabcount++;
212 $result .= $char . $newline . str_repeat($tab, $tabcount);
213 }
214 break;
215
216 case '}':
217 if ($inquote) {
218 $result .= $char;
219 }
220 else {
221 $tabcount--;
222 $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
223 }
224 break;
225
226 case ',':
227 if ($inquote || $inarray) {
228 $result .= $char;
229 }
230 else $result .= $char . $newline . str_repeat($tab, $tabcount);
231 break;
232
233 case '"':
234 $inquote = !$inquote;
235 $result .= $char;
236 break;
237
238 case '\\':
239 if ($inquote) {
240 $ignorenext = TRUE;
241 }
242 $result .= $char;
243 break;
244
245 case '[':
246 $inarray = TRUE;
247 $result .= $char;
248 break;
249
250 case ']':
251 $inarray = FALSE;
252 $result .= $char;
253 break;
254
255 default:
256 $result .= $char;
257 }
258 }
259 }
260
261 return $result;
262 }
263
264 /**
265 * @return array|int
266 */
267 public static function handle() {
268 $requestParams = CRM_Utils_Request::exportValues();
269
270 // Get the function name being called from the q parameter in the query string
271 $q = CRM_Utils_array::value('q', $requestParams);
272 // or for the rest interface, from fnName
273 $r = CRM_Utils_array::value('fnName', $requestParams);
274 if (!empty($r)) {
275 $q = $r;
276 }
277 $entity = CRM_Utils_array::value('entity', $requestParams);
278 if ( empty($entity) && !empty($q)) {
279 $args = explode('/', $q);
280 // If the function isn't in the civicrm namespace, reject the request.
281 if ($args[0] != 'civicrm') {
282 return self::error('Unknown function invocation.');
283 }
284
285 // If the query string is malformed, reject the request.
286 // Does this mean it will reject it
287 if ((count($args) != 3) && ($args[1] != 'ping')) {
288 return self::error('Unknown function invocation.');
289 }
290 $store = NULL;
291
292 if ($args[1] == 'ping') {
293 return self::ping();
294 }
295 } else {
296 // or the new format (entity+action)
297 $args = array();
298 $args[0] = 'civicrm';
299 $args[1] = CRM_Utils_array::value('entity', $requestParams);
300 $args[2] = CRM_Utils_array::value('action', $requestParams);
301 }
302
303
304 // Everyone should be required to provide the server key, so the whole
305 // interface can be disabled in more change to the configuration file.
306 // first check for civicrm site key
307 if (!CRM_Utils_System::authenticateKey(FALSE)) {
308 $docLink = CRM_Utils_System::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki");
309 $key = CRM_Utils_array::value('key', $requestParams);
310 if (empty($key)) {
311 return self::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink);
312 }
313 return self::error("FATAL: 'key' is incorrect. More info at: " . $docLink);
314 }
315
316
317 // At this point we know we are not calling ping which does not require authentication.
318 // Therefore, at this point we need to make sure we're working with a trusted user.
319 // Valid users are those who provide a valid server key and API key
320
321 $valid_user = FALSE;
322
323 // Check and see if a valid secret API key is provided.
324 $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
325 if (!$api_key || strtolower($api_key) == 'null') {
326 return self::error("FATAL: mandatory param 'api_key' (user key) missing");
327 }
328 $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
329
330 // If we didn't find a valid user, die
331 if (empty($valid_user)) {
332 return self::error("User API key invalid");
333 }
334
335 return self::process($args, self::buildParamList());
336 }
337
338 /**
339 * @param $args
340 * @param array $params
341 *
342 * @return array|int
343 */
344 public static function process(&$args, $params) {
345 $params['check_permissions'] = TRUE;
346 $fnName = $apiFile = NULL;
347 // clean up all function / class names. they should be alphanumeric and _ only
348 for ($i = 1; $i <= 3; $i++) {
349 if (!empty($args[$i])) {
350 $args[$i] = CRM_Utils_String::munge($args[$i]);
351 }
352 }
353
354 // incase of ajax functions className is passed in url
355 if (isset($params['className'])) {
356 $params['className'] = CRM_Utils_String::munge($params['className']);
357
358 // functions that are defined only in AJAX.php can be called via
359 // rest interface
360 if (!CRM_Core_Page_AJAX::checkAuthz('method', $params['className'], $params['fnName'])) {
361 return self::error('Unknown function invocation.');
362 }
363
364 return call_user_func(array($params['className'], $params['fnName']), $params);
365 }
366
367 if (!array_key_exists('version', $params)) {
368 $params['version'] = 3;
369 }
370
371 if ($params['version'] == 2) {
372 $result['is_error'] = 1;
373 $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST";
374 $result['deprecated'] = "Please upgrade to API v3";
375 return $result;
376 }
377
378 if ($_SERVER['REQUEST_METHOD'] == 'GET' && strtolower(substr( $args[2],0,3)) != 'get') {
379 // get only valid for non destructive methods
380 require_once 'api/v3/utils.php';
381 return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
382 array(
383 'IP' => $_SERVER['REMOTE_ADDR'],
384 'level' => 'security',
385 'referer' => $_SERVER['HTTP_REFERER'],
386 'reason' => 'Destructive HTTP GET',
387 )
388 );
389 }
390
391 // trap all fatal errors
392 $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal'));
393 $result = civicrm_api($args[1], $args[2], $params);
394 unset($errorScope);
395
396 if ($result === FALSE) {
397 return self::error('Unknown error.');
398 }
399 return $result;
400 }
401
402 /**
403 * @return array|mixed|null
404 */
405 public static function &buildParamList() {
406 $requestParams = CRM_Utils_Request::exportValues();
407 $params = array();
408
409 $skipVars = array(
410 'q' => 1,
411 'json' => 1,
412 'key' => 1,
413 'api_key' => 1,
414 'entity' => 1,
415 'action' => 1,
416 );
417
418 if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
419 $params = json_decode($requestParams['json'], TRUE);
420 if($params === NULL) {
421 CRM_Utils_JSON::output(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
422 }
423 }
424 foreach ($requestParams as $n => $v) {
425 if (!array_key_exists($n, $skipVars)) {
426 $params[$n] = $v;
427 }
428 }
429 if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) {
430 foreach ($requestParams['return'] as $key => $v) $params['return.' . $key] = 1;
431 }
432 return $params;
433 }
434
435 /**
436 * @param $pearError
437 */
438 public static function fatal($pearError) {
439 header('Content-Type: text/xml');
440 $error = array();
441 $error['code'] = $pearError->getCode();
442 $error['error_message'] = $pearError->getMessage();
443 $error['mode'] = $pearError->getMode();
444 $error['debug_info'] = $pearError->getDebugInfo();
445 $error['type'] = $pearError->getType();
446 $error['user_info'] = $pearError->getUserInfo();
447 $error['to_string'] = $pearError->toString();
448 $error['is_error'] = 1;
449
450 echo self::output($error);
451
452 CRM_Utils_System::civiExit();
453 }
454
455 public static function APIDoc() {
456
457 CRM_Utils_System::setTitle("API Parameters");
458 $template = CRM_Core_Smarty::singleton();
459 return CRM_Utils_System::theme(
460 $template->fetch('CRM/Core/APIDoc.tpl')
461 );
462 }
463
464 public static function ajaxDoc() {
465 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/api/explorer'));
466 }
467
468 /** used to load a template "inline", eg. for ajax, without having to build a menu for each template */
469 static function loadTemplate () {
470 $request = CRM_Utils_Request::retrieve( 'q', 'String');
471 if (false !== strpos($request, '..')) {
472 die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
473 }
474
475 $request = split ('/',$request);
476 $entity = _civicrm_api_get_camel_name($request[2]);
477 $tplfile=_civicrm_api_get_camel_name($request[3]);
478
479 $tpl = 'CRM/'.$entity.'/Page/Inline/'.$tplfile.'.tpl';
480 $smarty= CRM_Core_Smarty::singleton( );
481 CRM_Utils_System::setTitle( "$entity::$tplfile inline $tpl" );
482 if( !$smarty->template_exists($tpl) ){
483 header("Status: 404 Not Found");
484 die ("Can't find the requested template file templates/$tpl");
485 }
486 if (array_key_exists('id',$_GET)) {// special treatmenent, because it's often used
487 $smarty->assign ('id',(int)$_GET['id']);// an id is always positive
488 }
489 $pos = strpos (implode (array_keys ($_GET)),'<') ;
490
491 if ($pos !== false) {
492 die ("SECURITY FATAL: one of the param names contains &lt;");
493 }
494 $param = array_map( 'htmlentities' , $_GET);
495 unset($param['q']);
496 $smarty->assign_by_ref("request", $param);
497
498 if ( ! array_key_exists ( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ||
499 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" ) {
500
501 $smarty->assign( 'tplFile', $tpl );
502 $config = CRM_Core_Config::singleton();
503 $content = $smarty->fetch( 'CRM/common/'. strtolower($config->userFramework) .'.tpl' );
504
505 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) {
506 CRM_Utils_System::addHTMLHead($region->render(''));
507 }
508 CRM_Utils_System::appendTPLFile( $tpl, $content );
509
510 return CRM_Utils_System::theme($content);
511
512 } else {
513 $content = "<!-- .tpl file embeded: $tpl -->\n";
514 CRM_Utils_System::appendTPLFile( $tpl, $content );
515 echo $content . $smarty->fetch ($tpl);
516 CRM_Utils_System::civiExit( );
517 }
518 }
519
520 /** This is a wrapper so you can call an api via json (it returns json too)
521 * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals
522 * works for POST & GET (POST recommended)
523 **/
524 public static function ajaxJson() {
525 $requestParams = CRM_Utils_Request::exportValues();
526
527 require_once 'api/v3/utils.php';
528 // Why is $config undefined -- $config = CRM_Core_Config::singleton();
529 if (!$config->debug && (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
530 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
531 )) {
532 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
533 array(
534 'IP' => $_SERVER['REMOTE_ADDR'],
535 'level' => 'security',
536 'referer' => $_SERVER['HTTP_REFERER'],
537 'reason' => 'CSRF suspected',
538 )
539 );
540 CRM_Utils_JSON::output($error);
541 }
542 if (empty($requestParams['entity'])) {
543 CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity param'));
544 }
545 if (empty($requestParams['entity'])) {
546 CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity entity'));
547 }
548 if (!empty($requestParams['json'])) {
549 $params = json_decode($requestParams['json'], TRUE);
550 }
551 $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams));
552 $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams));
553 if (!is_array($params)) {
554 CRM_Utils_JSON::output(array('is_error' => 1, 'error_message', 'invalid json format: ?{"param_with_double_quote":"value"}'));
555 }
556
557 $params['check_permissions'] = TRUE;
558 $params['version'] = 3;
559 $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
560 if (!$params['sequential']) {
561 $params['sequential'] = 1;
562 }
563
564 // trap all fatal errors
565 $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal'));
566 $result = civicrm_api($entity, $action, $params);
567 unset($errorScope);
568
569 echo self::output($result);
570
571 CRM_Utils_System::civiExit();
572 }
573
574 public static function ajax() {
575 $requestParams = CRM_Utils_Request::exportValues();
576
577 // this is driven by the menu system, so we can use permissioning to
578 // restrict calls to this etc
579 // the request has to be sent by an ajax call. First line of protection against csrf
580 $config = CRM_Core_Config::singleton();
581 if (!$config->debug &&
582 (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
583 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
584 )
585 ) {
586 require_once 'api/v3/utils.php';
587 $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
588 array(
589 'IP' => $_SERVER['REMOTE_ADDR'],
590 'level' => 'security',
591 'referer' => $_SERVER['HTTP_REFERER'],
592 'reason' => 'CSRF suspected',
593 )
594 );
595 CRM_Utils_JSON::output($error);
596 }
597
598 $q = CRM_Utils_Array::value('fnName', $requestParams);
599 if (!$q) {
600 $entity = CRM_Utils_Array::value('entity', $requestParams);
601 $action = CRM_Utils_Array::value('action', $requestParams);
602 if (!$entity || !$action) {
603 $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
604 echo self::output($err);
605 CRM_Utils_System::civiExit();
606 }
607 $args = array('civicrm', $entity, $action);
608 }
609 else {
610 $args = explode('/', $q);
611 }
612
613 // get the class name, since all ajax functions pass className
614 $className = CRM_Utils_Array::value('className', $requestParams);
615
616 // If the function isn't in the civicrm namespace, reject the request.
617 if (($args[0] != 'civicrm' && count($args) != 3) && !$className) {
618 return self::error('Unknown function invocation.');
619 }
620
621 // Support for multiple api calls
622 if (isset($entity) && $entity === 'api3') {
623 $result = self::processMultiple();
624 }
625 else {
626 $result = self::process($args, self::buildParamList());
627 }
628
629 echo self::output($result);
630
631 CRM_Utils_System::civiExit();
632 }
633
634 /**
635 * Callback for multiple ajax api calls from CRM.api3()
636 * @return array
637 */
638 public static function processMultiple() {
639 $output = array();
640 foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
641 $args = array(
642 'civicrm',
643 $call[0],
644 $call[1],
645 );
646 $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, array()));
647 }
648 return $output;
649 }
650
651 /**
652 * @return array|NULL NULL if execution should proceed; array if the response is already known
653 */
654 public function loadCMSBootstrap() {
655 $requestParams = CRM_Utils_Request::exportValues();
656 $q = CRM_Utils_array::value('q', $requestParams);
657 $args = explode('/', $q);
658
659 // Proceed with bootstrap for "?entity=X&action=Y"
660 // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
661 if (!empty($q)) {
662 if (count($args) == 2 && $args[1] == 'ping') {
663 return NULL; // this is pretty wonky but maybe there's some reason I can't see
664 }
665 if (count($args) != 3) {
666 return self::error('ERROR: Malformed REST path');
667 }
668 if ($args[0] != 'civicrm') {
669 return self::error('ERROR: Malformed REST path');
670 }
671 // Therefore we have reasonably well-formed "?q=civicrm/X/Y"
672 }
673
674 if (!CRM_Utils_System::authenticateKey(FALSE)) {
675 // FIXME: At time of writing, this doesn't actually do anything because
676 // authenticateKey abends, but that's a bad behavior which sends a
677 // malformed response.
678 return self::error('Failed to authenticate key');
679 }
680
681 $uid = NULL;
682 if (!$uid) {
683 $store = NULL;
684 $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
685 if (empty($api_key)) {
686 return self::error("FATAL: mandatory param 'api_key' (user key) missing");
687 }
688 $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
689 if ($contact_id) {
690 $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id);
691 }
692 }
693
694 if ($uid) {
695 CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
696 return NULL;
697 }
698 else {
699 return self::error('ERROR: No CMS user associated with given api-key');
700 }
701 }
702 }