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