Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
7e9e8871 | 4 | | CiviCRM version 4.7 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
e7112fa7 | 6 | | Copyright CiviCRM LLC (c) 2004-2015 | |
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 | |
e7112fa7 | 32 | * @copyright CiviCRM LLC (c) 2004-2015 |
6a488035 TO |
33 | * |
34 | */ | |
35 | class 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 | 147 | if (!empty($requestParams['json'])) { |
3eec106c | 148 | if (!empty($requestParams['prettyprint'])) { |
b308e50d | 149 | // Don't set content-type header for api explorer output |
108bcf37 | 150 | return self::jsonFormated(array_merge($result)); |
6a488035 | 151 | } |
b308e50d | 152 | CRM_Utils_System::setHttpHeader('Content-Type', 'application/json'); |
108bcf37 | 153 | return json_encode(array_merge($result)); |
6a488035 TO |
154 | } |
155 | ||
6a488035 | 156 | if (isset($result['count'])) { |
6a488035 | 157 | $count = ' count="' . $result['count'] . '" '; |
6a488035 | 158 | } |
a3e55d9c TO |
159 | else { |
160 | $count = ""; | |
e7292422 | 161 | } |
6a488035 TO |
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) { | |
59a4addf AN |
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 | } | |
6a488035 TO |
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 | ||
5bc392e6 | 185 | /** |
108bcf37 CW |
186 | * @param $data |
187 | * | |
188 | * @deprecated - switch to native JSON_PRETTY_PRINT when we drop support for php 5.3 | |
5bc392e6 EM |
189 | * |
190 | * @return string | |
191 | */ | |
108bcf37 CW |
192 | public static function jsonFormated($data) { |
193 | // If php is 5.4+ we can use the native method | |
194 | if (defined('JSON_PRETTY_PRINT')) { | |
695ad4c7 | 195 | return json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE); |
108bcf37 CW |
196 | } |
197 | ||
198 | // PHP 5.3 shim | |
199 | $json = str_replace('\/', '/', json_encode($data)); | |
353ffa53 TO |
200 | $tabcount = 0; |
201 | $result = ''; | |
202 | $inquote = FALSE; | |
203 | $inarray = FALSE; | |
6a488035 TO |
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 | } | |
a3e55d9c TO |
243 | else { |
244 | $result .= $char . $newline . str_repeat($tab, $tabcount); | |
e7292422 | 245 | } |
6a488035 TO |
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 | ||
5bc392e6 EM |
279 | /** |
280 | * @return array|int | |
281 | */ | |
00be9182 | 282 | public static function handle() { |
ba56a28f TO |
283 | $requestParams = CRM_Utils_Request::exportValues(); |
284 | ||
6a488035 | 285 | // Get the function name being called from the q parameter in the query string |
ba56a28f | 286 | $q = CRM_Utils_array::value('q', $requestParams); |
6a488035 | 287 | // or for the rest interface, from fnName |
ba56a28f | 288 | $r = CRM_Utils_array::value('fnName', $requestParams); |
6a488035 TO |
289 | if (!empty($r)) { |
290 | $q = $r; | |
291 | } | |
775d38eb | 292 | $entity = CRM_Utils_array::value('entity', $requestParams); |
481a74f4 | 293 | if (empty($entity) && !empty($q)) { |
6a488035 TO |
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. | |
7f2d6a61 TO |
301 | // Does this mean it will reject it |
302 | if ((count($args) != 3) && ($args[1] != 'ping')) { | |
6a488035 TO |
303 | return self::error('Unknown function invocation.'); |
304 | } | |
305 | $store = NULL; | |
f813f78e | 306 | |
7f2d6a61 | 307 | if ($args[1] == 'ping') { |
6a488035 TO |
308 | return self::ping(); |
309 | } | |
0db6c3e1 TO |
310 | } |
311 | else { | |
650ff635 | 312 | // or the api format (entity+action) |
7f2d6a61 TO |
313 | $args = array(); |
314 | $args[0] = 'civicrm'; | |
ba56a28f TO |
315 | $args[1] = CRM_Utils_array::value('entity', $requestParams); |
316 | $args[2] = CRM_Utils_array::value('action', $requestParams); | |
6a488035 | 317 | } |
f813f78e | 318 | |
6a488035 TO |
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. | |
6a488035 TO |
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"); | |
ba56a28f | 324 | $key = CRM_Utils_array::value('key', $requestParams); |
6a488035 TO |
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 | ||
7f2d6a61 | 331 | // At this point we know we are not calling ping which does not require authentication. |
650ff635 | 332 | // Therefore we now need a valid server key and API key |
6a488035 | 333 | |
7f2d6a61 TO |
334 | // Check and see if a valid secret API key is provided. |
335 | $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST'); | |
336 | if (!$api_key || strtolower($api_key) == 'null') { | |
337 | return self::error("FATAL: mandatory param 'api_key' (user key) missing"); | |
6a488035 | 338 | } |
7f2d6a61 | 339 | $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key'); |
6a488035 | 340 | |
7f2d6a61 | 341 | // If we didn't find a valid user, die |
6a488035 | 342 | if (empty($valid_user)) { |
7f2d6a61 | 343 | return self::error("User API key invalid"); |
6a488035 TO |
344 | } |
345 | ||
a323a20f | 346 | return self::process($args, self::buildParamList()); |
6a488035 TO |
347 | } |
348 | ||
5bc392e6 EM |
349 | /** |
350 | * @param $args | |
c490a46a | 351 | * @param array $params |
5bc392e6 EM |
352 | * |
353 | * @return array|int | |
354 | */ | |
00be9182 | 355 | public static function process(&$args, $params) { |
6a488035 TO |
356 | $params['check_permissions'] = TRUE; |
357 | $fnName = $apiFile = NULL; | |
358 | // clean up all function / class names. they should be alphanumeric and _ only | |
359 | for ($i = 1; $i <= 3; $i++) { | |
360 | if (!empty($args[$i])) { | |
361 | $args[$i] = CRM_Utils_String::munge($args[$i]); | |
362 | } | |
363 | } | |
364 | ||
365 | // incase of ajax functions className is passed in url | |
366 | if (isset($params['className'])) { | |
367 | $params['className'] = CRM_Utils_String::munge($params['className']); | |
368 | ||
369 | // functions that are defined only in AJAX.php can be called via | |
370 | // rest interface | |
371 | if (!CRM_Core_Page_AJAX::checkAuthz('method', $params['className'], $params['fnName'])) { | |
372 | return self::error('Unknown function invocation.'); | |
373 | } | |
374 | ||
375 | return call_user_func(array($params['className'], $params['fnName']), $params); | |
376 | } | |
377 | ||
378 | if (!array_key_exists('version', $params)) { | |
379 | $params['version'] = 3; | |
380 | } | |
381 | ||
382 | if ($params['version'] == 2) { | |
383 | $result['is_error'] = 1; | |
384 | $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST"; | |
385 | $result['deprecated'] = "Please upgrade to API v3"; | |
386 | return $result; | |
387 | } | |
388 | ||
92c11e8c J |
389 | if ($_SERVER['REQUEST_METHOD'] == 'GET' && |
390 | strtolower(substr($args[2], 0, 3)) != 'get' && | |
391 | strtolower($args[2] != 'check')) { | |
f9e16e9a | 392 | // get only valid for non destructive methods |
6a488035 TO |
393 | require_once 'api/v3/utils.php'; |
394 | return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.", | |
395 | array( | |
396 | 'IP' => $_SERVER['REMOTE_ADDR'], | |
397 | 'level' => 'security', | |
398 | 'referer' => $_SERVER['HTTP_REFERER'], | |
399 | 'reason' => 'Destructive HTTP GET', | |
400 | ) | |
401 | ); | |
402 | } | |
403 | ||
404 | // trap all fatal errors | |
ca32aecc | 405 | $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); |
6a488035 | 406 | $result = civicrm_api($args[1], $args[2], $params); |
ca32aecc | 407 | unset($errorScope); |
6a488035 TO |
408 | |
409 | if ($result === FALSE) { | |
410 | return self::error('Unknown error.'); | |
411 | } | |
412 | return $result; | |
413 | } | |
414 | ||
5bc392e6 EM |
415 | /** |
416 | * @return array|mixed|null | |
417 | */ | |
00be9182 | 418 | public static function &buildParamList() { |
ba56a28f | 419 | $requestParams = CRM_Utils_Request::exportValues(); |
6a488035 TO |
420 | $params = array(); |
421 | ||
422 | $skipVars = array( | |
423 | 'q' => 1, | |
424 | 'json' => 1, | |
425 | 'key' => 1, | |
426 | 'api_key' => 1, | |
427 | 'entity' => 1, | |
428 | 'action' => 1, | |
429 | ); | |
430 | ||
353ffa53 | 431 | if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") { |
ba56a28f | 432 | $params = json_decode($requestParams['json'], TRUE); |
22e263ad | 433 | if ($params === NULL) { |
ecdef330 | 434 | CRM_Utils_JSON::output(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.')); |
6a488035 TO |
435 | } |
436 | } | |
ba56a28f | 437 | foreach ($requestParams as $n => $v) { |
6a488035 TO |
438 | if (!array_key_exists($n, $skipVars)) { |
439 | $params[$n] = $v; | |
440 | } | |
441 | } | |
ba56a28f | 442 | if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) { |
a3e55d9c TO |
443 | foreach ($requestParams['return'] as $key => $v) { |
444 | $params['return.' . $key] = 1; | |
e7292422 | 445 | } |
6a488035 TO |
446 | } |
447 | return $params; | |
448 | } | |
449 | ||
5bc392e6 EM |
450 | /** |
451 | * @param $pearError | |
452 | */ | |
00be9182 | 453 | public static function fatal($pearError) { |
d42a224c | 454 | CRM_Utils_System::setHttpHeader('Content-Type', 'text/xml'); |
6a488035 TO |
455 | $error = array(); |
456 | $error['code'] = $pearError->getCode(); | |
457 | $error['error_message'] = $pearError->getMessage(); | |
458 | $error['mode'] = $pearError->getMode(); | |
459 | $error['debug_info'] = $pearError->getDebugInfo(); | |
460 | $error['type'] = $pearError->getType(); | |
461 | $error['user_info'] = $pearError->getUserInfo(); | |
462 | $error['to_string'] = $pearError->toString(); | |
463 | $error['is_error'] = 1; | |
464 | ||
465 | echo self::output($error); | |
466 | ||
467 | CRM_Utils_System::civiExit(); | |
468 | } | |
469 | ||
d5cc0fc2 | 470 | /** |
471 | * used to load a template "inline", eg. for ajax, without having to build a menu for each template | |
472 | */ | |
473 | public static function loadTemplate() { | |
481a74f4 | 474 | $request = CRM_Utils_Request::retrieve('q', 'String'); |
e7292422 | 475 | if (FALSE !== strpos($request, '..')) { |
6a488035 TO |
476 | die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org"); |
477 | } | |
478 | ||
d3e86119 | 479 | $request = explode('/', $request); |
6a488035 | 480 | $entity = _civicrm_api_get_camel_name($request[2]); |
e7292422 | 481 | $tplfile = _civicrm_api_get_camel_name($request[3]); |
6a488035 | 482 | |
92fcb95f | 483 | $tpl = 'CRM/' . $entity . '/Page/Inline/' . $tplfile . '.tpl'; |
481a74f4 TO |
484 | $smarty = CRM_Core_Smarty::singleton(); |
485 | CRM_Utils_System::setTitle("$entity::$tplfile inline $tpl"); | |
486 | if (!$smarty->template_exists($tpl)) { | |
d42a224c | 487 | CRM_Utils_System::setHttpHeader("Status", "404 Not Found"); |
6a488035 TO |
488 | die ("Can't find the requested template file templates/$tpl"); |
489 | } | |
e7292422 TO |
490 | if (array_key_exists('id', $_GET)) {// special treatmenent, because it's often used |
491 | $smarty->assign('id', (int) $_GET['id']);// an id is always positive | |
6a488035 | 492 | } |
e7292422 | 493 | $pos = strpos(implode(array_keys($_GET)), '<'); |
6a488035 | 494 | |
e7292422 | 495 | if ($pos !== FALSE) { |
6a488035 TO |
496 | die ("SECURITY FATAL: one of the param names contains <"); |
497 | } | |
481a74f4 | 498 | $param = array_map('htmlentities', $_GET); |
6a488035 TO |
499 | unset($param['q']); |
500 | $smarty->assign_by_ref("request", $param); | |
501 | ||
353ffa53 TO |
502 | if (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || |
503 | $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" | |
504 | ) { | |
6a488035 | 505 | |
481a74f4 | 506 | $smarty->assign('tplFile', $tpl); |
e7292422 | 507 | $config = CRM_Core_Config::singleton(); |
353ffa53 | 508 | $content = $smarty->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl'); |
6a488035 | 509 | |
e7292422 TO |
510 | if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) { |
511 | CRM_Utils_System::addHTMLHead($region->render('')); | |
512 | } | |
481a74f4 | 513 | CRM_Utils_System::appendTPLFile($tpl, $content); |
6a488035 | 514 | |
e7292422 | 515 | return CRM_Utils_System::theme($content); |
6a488035 | 516 | |
0db6c3e1 TO |
517 | } |
518 | else { | |
b44e3f84 | 519 | $content = "<!-- .tpl file embedded: $tpl -->\n"; |
481a74f4 | 520 | CRM_Utils_System::appendTPLFile($tpl, $content); |
e7292422 | 521 | echo $content . $smarty->fetch($tpl); |
481a74f4 | 522 | CRM_Utils_System::civiExit(); |
6a488035 TO |
523 | } |
524 | } | |
525 | ||
d5cc0fc2 | 526 | /** |
527 | * This is a wrapper so you can call an api via json (it returns json too) | |
6a488035 TO |
528 | * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals |
529 | * works for POST & GET (POST recommended) | |
d5cc0fc2 | 530 | */ |
00be9182 | 531 | public static function ajaxJson() { |
ba56a28f TO |
532 | $requestParams = CRM_Utils_Request::exportValues(); |
533 | ||
6a488035 | 534 | require_once 'api/v3/utils.php'; |
650ff635 | 535 | $config = CRM_Core_Config::singleton(); |
7f2d6a61 | 536 | if (!$config->debug && (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || |
6a488035 | 537 | $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" |
353ffa53 TO |
538 | ) |
539 | ) { | |
e4176358 | 540 | $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", |
6a488035 TO |
541 | array( |
542 | 'IP' => $_SERVER['REMOTE_ADDR'], | |
543 | 'level' => 'security', | |
544 | 'referer' => $_SERVER['HTTP_REFERER'], | |
545 | 'reason' => 'CSRF suspected', | |
546 | ) | |
547 | ); | |
ecdef330 | 548 | CRM_Utils_JSON::output($error); |
6a488035 | 549 | } |
ba56a28f | 550 | if (empty($requestParams['entity'])) { |
ecdef330 | 551 | CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity param')); |
6a488035 | 552 | } |
ba56a28f | 553 | if (empty($requestParams['entity'])) { |
ecdef330 | 554 | CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity entity')); |
6a488035 | 555 | } |
ba56a28f TO |
556 | if (!empty($requestParams['json'])) { |
557 | $params = json_decode($requestParams['json'], TRUE); | |
6a488035 | 558 | } |
ba56a28f TO |
559 | $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams)); |
560 | $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams)); | |
6a488035 | 561 | if (!is_array($params)) { |
353ffa53 TO |
562 | CRM_Utils_JSON::output(array( |
563 | 'is_error' => 1, | |
d5cc0fc2 | 564 | 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}', |
353ffa53 | 565 | )); |
6a488035 TO |
566 | } |
567 | ||
568 | $params['check_permissions'] = TRUE; | |
569 | $params['version'] = 3; | |
ba56a28f | 570 | $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions |
6a488035 TO |
571 | if (!$params['sequential']) { |
572 | $params['sequential'] = 1; | |
573 | } | |
ca32aecc | 574 | |
6a488035 | 575 | // trap all fatal errors |
ca32aecc | 576 | $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); |
6a488035 | 577 | $result = civicrm_api($entity, $action, $params); |
ca32aecc | 578 | unset($errorScope); |
6a488035 TO |
579 | |
580 | echo self::output($result); | |
581 | ||
582 | CRM_Utils_System::civiExit(); | |
583 | } | |
584 | ||
b896fa44 EM |
585 | /** |
586 | * Run ajax request. | |
587 | * | |
588 | * @return array | |
589 | */ | |
00be9182 | 590 | public static function ajax() { |
ba56a28f TO |
591 | $requestParams = CRM_Utils_Request::exportValues(); |
592 | ||
6a488035 TO |
593 | // this is driven by the menu system, so we can use permissioning to |
594 | // restrict calls to this etc | |
595 | // the request has to be sent by an ajax call. First line of protection against csrf | |
596 | $config = CRM_Core_Config::singleton(); | |
7f2d6a61 | 597 | if (!$config->debug && |
6a488035 TO |
598 | (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || |
599 | $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" | |
600 | ) | |
601 | ) { | |
602 | require_once 'api/v3/utils.php'; | |
a323a20f | 603 | $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", |
6a488035 TO |
604 | array( |
605 | 'IP' => $_SERVER['REMOTE_ADDR'], | |
606 | 'level' => 'security', | |
607 | 'referer' => $_SERVER['HTTP_REFERER'], | |
608 | 'reason' => 'CSRF suspected', | |
609 | ) | |
610 | ); | |
ecdef330 | 611 | CRM_Utils_JSON::output($error); |
6a488035 TO |
612 | } |
613 | ||
ba56a28f | 614 | $q = CRM_Utils_Array::value('fnName', $requestParams); |
6a488035 | 615 | if (!$q) { |
ba56a28f TO |
616 | $entity = CRM_Utils_Array::value('entity', $requestParams); |
617 | $action = CRM_Utils_Array::value('action', $requestParams); | |
6a488035 TO |
618 | if (!$entity || !$action) { |
619 | $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1); | |
620 | echo self::output($err); | |
621 | CRM_Utils_System::civiExit(); | |
622 | } | |
623 | $args = array('civicrm', $entity, $action); | |
624 | } | |
625 | else { | |
626 | $args = explode('/', $q); | |
627 | } | |
628 | ||
629 | // get the class name, since all ajax functions pass className | |
ba56a28f | 630 | $className = CRM_Utils_Array::value('className', $requestParams); |
6a488035 TO |
631 | |
632 | // If the function isn't in the civicrm namespace, reject the request. | |
633 | if (($args[0] != 'civicrm' && count($args) != 3) && !$className) { | |
634 | return self::error('Unknown function invocation.'); | |
635 | } | |
636 | ||
a323a20f CW |
637 | // Support for multiple api calls |
638 | if (isset($entity) && $entity === 'api3') { | |
639 | $result = self::processMultiple(); | |
640 | } | |
641 | else { | |
642 | $result = self::process($args, self::buildParamList()); | |
643 | } | |
6a488035 TO |
644 | |
645 | echo self::output($result); | |
646 | ||
647 | CRM_Utils_System::civiExit(); | |
648 | } | |
649 | ||
a323a20f CW |
650 | /** |
651 | * Callback for multiple ajax api calls from CRM.api3() | |
652 | * @return array | |
653 | */ | |
00be9182 | 654 | public static function processMultiple() { |
a323a20f CW |
655 | $output = array(); |
656 | foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) { | |
657 | $args = array( | |
658 | 'civicrm', | |
659 | $call[0], | |
660 | $call[1], | |
661 | ); | |
662 | $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, array())); | |
663 | } | |
664 | return $output; | |
665 | } | |
666 | ||
7f2d6a61 | 667 | /** |
72b3a70c CW |
668 | * @return array|NULL |
669 | * NULL if execution should proceed; array if the response is already known | |
7f2d6a61 | 670 | */ |
00be9182 | 671 | public function loadCMSBootstrap() { |
ba56a28f TO |
672 | $requestParams = CRM_Utils_Request::exportValues(); |
673 | $q = CRM_Utils_array::value('q', $requestParams); | |
6a488035 TO |
674 | $args = explode('/', $q); |
675 | ||
7f2d6a61 TO |
676 | // Proceed with bootstrap for "?entity=X&action=Y" |
677 | // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping" | |
678 | if (!empty($q)) { | |
679 | if (count($args) == 2 && $args[1] == 'ping') { | |
680 | return NULL; // this is pretty wonky but maybe there's some reason I can't see | |
681 | } | |
682 | if (count($args) != 3) { | |
683 | return self::error('ERROR: Malformed REST path'); | |
684 | } | |
685 | if ($args[0] != 'civicrm') { | |
686 | return self::error('ERROR: Malformed REST path'); | |
687 | } | |
688 | // Therefore we have reasonably well-formed "?q=civicrm/X/Y" | |
6a488035 TO |
689 | } |
690 | ||
691 | if (!CRM_Utils_System::authenticateKey(FALSE)) { | |
7f2d6a61 TO |
692 | // FIXME: At time of writing, this doesn't actually do anything because |
693 | // authenticateKey abends, but that's a bad behavior which sends a | |
694 | // malformed response. | |
695 | return self::error('Failed to authenticate key'); | |
6a488035 TO |
696 | } |
697 | ||
698 | $uid = NULL; | |
6a488035 | 699 | if (!$uid) { |
353ffa53 TO |
700 | $store = NULL; |
701 | $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST'); | |
7f2d6a61 TO |
702 | if (empty($api_key)) { |
703 | return self::error("FATAL: mandatory param 'api_key' (user key) missing"); | |
704 | } | |
6a488035 TO |
705 | $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key'); |
706 | if ($contact_id) { | |
707 | $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id); | |
708 | } | |
709 | } | |
710 | ||
711 | if ($uid) { | |
712 | CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE); | |
7f2d6a61 TO |
713 | return NULL; |
714 | } | |
715 | else { | |
716 | return self::error('ERROR: No CMS user associated with given api-key'); | |
6a488035 TO |
717 | } |
718 | } | |
96025800 | 719 | |
6a488035 | 720 | } |