Merge pull request #15348 from civicrm/5.18
[civicrm-core.git] / CRM / Api4 / Page / AJAX.php
1 <?php
2
3 class CRM_Api4_Page_AJAX extends CRM_Core_Page {
4
5 /**
6 * Handler for api4 ajax requests
7 */
8 public function run() {
9 try {
10 // Call multiple
11 if (empty($this->urlPath[3])) {
12 $calls = CRM_Utils_Request::retrieve('calls', 'String', CRM_Core_DAO::$_nullObject, TRUE, NULL, 'POST', TRUE);
13 $calls = json_decode($calls, TRUE);
14 $response = [];
15 foreach ($calls as $index => $call) {
16 $response[$index] = call_user_func_array([$this, 'execute'], $call);
17 }
18 }
19 // Call single
20 else {
21 $entity = $this->urlPath[3];
22 $action = $this->urlPath[4];
23 $params = CRM_Utils_Request::retrieve('params', 'String');
24 $params = $params ? json_decode($params, TRUE) : [];
25 $index = CRM_Utils_Request::retrieve('index', 'String');
26 $response = $this->execute($entity, $action, $params, $index);
27 }
28 }
29 catch (Exception $e) {
30 http_response_code(500);
31 $response = [
32 'error_code' => $e->getCode(),
33 ];
34 if (CRM_Core_Permission::check('view debug output')) {
35 $response['error_message'] = $e->getMessage();
36 if (\Civi::settings()->get('backtrace')) {
37 $response['backtrace'] = $e->getTrace();
38 }
39 }
40 }
41 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
42 echo json_encode($response);
43 CRM_Utils_System::civiExit();
44 }
45
46 /**
47 * Run api call & prepare result for json encoding
48 *
49 * @param string $entity
50 * @param string $action
51 * @param array $params
52 * @param string $index
53 * @return array
54 */
55 protected function execute($entity, $action, $params = [], $index = NULL) {
56 $params['checkPermissions'] = TRUE;
57
58 // Handle numeric indexes later so we can get the count
59 $itemAt = CRM_Utils_Type::validate($index, 'Integer', FALSE);
60
61 $result = civicrm_api4($entity, $action, $params, isset($itemAt) ? NULL : $index);
62
63 // Convert arrayObject into something more suitable for json
64 $vals = ['values' => isset($itemAt) ? $result->itemAt($itemAt) : (array) $result];
65 foreach (get_class_vars(get_class($result)) as $key => $val) {
66 $vals[$key] = $result->$key;
67 }
68 $vals['count'] = $result->count();
69 return $vals;
70 }
71
72 }