Merge pull request #15810 from eileenmcnaughton/mem_fix
[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 * $Id$
18 *
19 */
20 class CRM_Api4_Page_AJAX extends CRM_Core_Page {
21
22 /**
23 * Handler for api4 ajax requests
24 */
25 public function run() {
26 try {
27 // Call multiple
28 if (empty($this->urlPath[3])) {
29 $calls = CRM_Utils_Request::retrieve('calls', 'String', CRM_Core_DAO::$_nullObject, TRUE, NULL, 'POST', TRUE);
30 $calls = json_decode($calls, TRUE);
31 $response = [];
32 foreach ($calls as $index => $call) {
33 $response[$index] = call_user_func_array([$this, 'execute'], $call);
34 }
35 }
36 // Call single
37 else {
38 $entity = $this->urlPath[3];
39 $action = $this->urlPath[4];
40 $params = CRM_Utils_Request::retrieve('params', 'String');
41 $params = $params ? json_decode($params, TRUE) : [];
42 $index = CRM_Utils_Request::retrieve('index', 'String');
43 $response = $this->execute($entity, $action, $params, $index);
44 }
45 }
46 catch (Exception $e) {
47 http_response_code(500);
48 $response = [
49 'error_code' => $e->getCode(),
50 ];
51 if (CRM_Core_Permission::check('view debug output')) {
52 $response['error_message'] = $e->getMessage();
53 if (\Civi::settings()->get('backtrace')) {
54 $response['backtrace'] = $e->getTrace();
55 }
56 }
57 }
58 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
59 echo json_encode($response);
60 CRM_Utils_System::civiExit();
61 }
62
63 /**
64 * Run api call & prepare result for json encoding
65 *
66 * @param string $entity
67 * @param string $action
68 * @param array $params
69 * @param string $index
70 * @return array
71 */
72 protected function execute($entity, $action, $params = [], $index = NULL) {
73 $params['checkPermissions'] = TRUE;
74
75 // Handle numeric indexes later so we can get the count
76 $itemAt = CRM_Utils_Type::validate($index, 'Integer', FALSE);
77
78 $result = civicrm_api4($entity, $action, $params, isset($itemAt) ? NULL : $index);
79
80 // Convert arrayObject into something more suitable for json
81 $vals = ['values' => isset($itemAt) ? $result->itemAt($itemAt) : (array) $result];
82 foreach (get_class_vars(get_class($result)) as $key => $val) {
83 $vals[$key] = $result->$key;
84 }
85 $vals['count'] = $result->count();
86 return $vals;
87 }
88
89 }