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