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