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