Merge pull request #21729 from MegaphoneJon/financial-181-rc
[civicrm-core.git] / CRM / Api4 / Page / AJAX.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
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 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18 class CRM_Api4_Page_AJAX extends CRM_Core_Page {
19
20 /**
21 * Handler for api4 ajax requests
22 */
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"
27 )
28 ) {
29 $response = [
30 'error_code' => 401,
31 'error_message' => "SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api4().",
32 ];
33 Civi::log()->debug("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api4().",
34 [
35 'IP' => $_SERVER['REMOTE_ADDR'],
36 'level' => 'security',
37 'referer' => $_SERVER['HTTP_REFERER'],
38 'reason' => 'CSRF suspected',
39 ]
40 );
41 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
42 echo json_encode($response);
43 CRM_Utils_System::civiExit();
44 }
45 if ($_SERVER['REQUEST_METHOD'] == 'GET' &&
46 strtolower(substr($this->urlPath[4], 0, 3)) != 'get') {
47 $response = [
48 'error_code' => 400,
49 'error_message' => "SECURITY: All requests that modify the database must be http POST, not GET.",
50 ];
51 Civi::log()->debug("SECURITY: All requests that modify the database must be http POST, not GET.",
52 [
53 'IP' => $_SERVER['REMOTE_ADDR'],
54 'level' => 'security',
55 'referer' => $_SERVER['HTTP_REFERER'],
56 'reason' => 'Destructive HTTP GET',
57 ]
58 );
59 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
60 echo json_encode($response);
61 CRM_Utils_System::civiExit();
62 }
63 try {
64 // Call multiple
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);
68 $response = [];
69 foreach ($calls as $index => $call) {
70 $response[$index] = call_user_func_array([$this, 'execute'], $call);
71 }
72 }
73 // Call single
74 else {
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);
81 }
82 }
83 catch (Exception $e) {
84 $statusMap = [
85 \Civi\API\Exception\UnauthorizedException::class => 403,
86 ];
87 http_response_code($statusMap[get_class($e)] ?? 500);
88 $response = [];
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();
95 }
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();
100 }
101 if (\Civi::settings()->get('backtrace')) {
102 // Would prefer getTrace() but that causes json_encode to bomb
103 $response['debug']['backtrace'] = $e->getTraceAsString();
104 }
105 }
106 }
107 else {
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)', [
111 1 => $error_id,
112 ]);
113 \Civi::log()->debug('AJAX Error ({error_id}): failed with exception', [
114 'error_id' => $error_id,
115 'exception' => $e,
116 ]);
117 }
118 }
119 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
120 echo json_encode($response);
121 CRM_Utils_System::civiExit();
122 }
123
124 /**
125 * Run api call & prepare result for json encoding
126 *
127 * @param string $entity
128 * @param string $action
129 * @param array $params
130 * @param string $index
131 * @return array
132 */
133 protected function execute($entity, $action, $params = [], $index = NULL) {
134 $params['checkPermissions'] = TRUE;
135
136 // Handle numeric indexes later so we can get the count
137 $itemAt = CRM_Utils_Type::validate($index, 'Integer', FALSE);
138
139 $result = civicrm_api4($entity, $action, $params, isset($itemAt) ? NULL : $index);
140
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;
145 }
146 unset($vals['rowCount']);
147 $vals['count'] = $result->count();
148 return $vals;
149 }
150
151 }