4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 class CRM_Api4_Page_AJAX
extends CRM_Core_Page
{
21 * Handler for api4 ajax requests
23 public function run() {
24 $config = CRM_Core_Config
::singleton();
25 if (!$config->debug
&& (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) ||
26 $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest"
31 'error_message' => "SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api4().",
33 Civi
::log()->debug("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api4().",
35 'IP' => $_SERVER['REMOTE_ADDR'],
36 'level' => 'security',
37 'referer' => $_SERVER['HTTP_REFERER'],
38 'reason' => 'CSRF suspected',
41 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/json');
42 echo json_encode($response);
43 CRM_Utils_System
::civiExit();
45 if ($_SERVER['REQUEST_METHOD'] == 'GET' &&
46 strtolower(substr($this->urlPath
[4], 0, 3)) != 'get') {
49 'error_message' => "SECURITY: All requests that modify the database must be http POST, not GET.",
51 Civi
::log()->debug("SECURITY: All requests that modify the database must be http POST, not GET.",
53 'IP' => $_SERVER['REMOTE_ADDR'],
54 'level' => 'security',
55 'referer' => $_SERVER['HTTP_REFERER'],
56 'reason' => 'Destructive HTTP GET',
59 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/json');
60 echo json_encode($response);
61 CRM_Utils_System
::civiExit();
65 if (empty($this->urlPath
[3])) {
66 $calls = CRM_Utils_Request
::retrieve('calls', 'String', CRM_Core_DAO
::$_nullObject, TRUE, NULL, 'POST');
67 $calls = json_decode($calls, TRUE);
69 foreach ($calls as $index => $call) {
70 $response[$index] = call_user_func_array([$this, 'execute'], $call);
75 $entity = $this->urlPath
[3];
76 $action = $this->urlPath
[4];
77 $params = CRM_Utils_Request
::retrieve('params', 'String');
78 $params = $params ?
json_decode($params, TRUE) : [];
79 $index = CRM_Utils_Request
::retrieve('index', 'String');
80 $response = $this->execute($entity, $action, $params, $index);
83 catch (Exception
$e) {
85 \Civi\API\Exception\UnauthorizedException
::class => 403,
87 http_response_code($statusMap[get_class($e)] ??
500);
89 if (CRM_Core_Permission
::check('view debug output')) {
90 $response['error_code'] = $e->getCode();
91 $response['error_message'] = $e->getMessage();
92 if (!empty($params['debug'])) {
93 if (method_exists($e, 'getUserInfo')) {
94 $response['debug']['info'] = $e->getUserInfo();
96 $cause = method_exists($e, 'getCause') ?
$e->getCause() : $e;
97 if ($cause instanceof \DB_Error
) {
98 $response['debug']['db_error'] = \DB
::errorMessage($cause->getCode());
99 $response['debug']['sql'][] = $cause->getDebugInfo();
101 if (\Civi
::settings()->get('backtrace')) {
102 // Would prefer getTrace() but that causes json_encode to bomb
103 $response['debug']['backtrace'] = $e->getTraceAsString();
108 $error_id = rtrim(chunk_split(CRM_Utils_String
::createRandom(12, CRM_Utils_String
::ALPHANUMERIC
), 4, '-'), '-');
109 $response['error_code'] = '1';
110 $response['error_message'] = ts('Sorry an error occurred and your request was not completed. (Error ID: %1)', [
113 \Civi
::log()->debug('AJAX Error ({error_id}): failed with exception', [
114 'error_id' => $error_id,
119 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/json');
120 echo json_encode($response);
121 CRM_Utils_System
::civiExit();
125 * Run api call & prepare result for json encoding
127 * @param string $entity
128 * @param string $action
129 * @param array $params
130 * @param string $index
133 protected function execute($entity, $action, $params = [], $index = NULL) {
134 $params['checkPermissions'] = TRUE;
136 // Handle numeric indexes later so we can get the count
137 $itemAt = CRM_Utils_Type
::validate($index, 'Integer', FALSE);
139 $result = civicrm_api4($entity, $action, $params, isset($itemAt) ?
NULL : $index);
141 // Convert arrayObject into something more suitable for json
142 $vals = ['values' => isset($itemAt) ?
$result->itemAt($itemAt) : (array) $result];
143 foreach (get_class_vars(get_class($result)) as $key => $val) {
144 $vals[$key] = $result->$key;
146 unset($vals['rowCount']);
147 $vals['count'] = $result->count();