Merge pull request #14840 from MegaphoneJon/core-1130
[civicrm-core.git] / Civi / API / Subscriber / ChainSubscriber.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 namespace Civi\API\Subscriber;
29
30 use Civi\API\Events;
31 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
32
33 /**
34 * The ChainSubscriber looks for API parameters which specify a nested or
35 * chained API call. For example:
36 *
37 * @code
38 * $result = civicrm_api('Contact', 'create', array(
39 * 'version' => 3,
40 * 'first_name' => 'Amy',
41 * 'api.Email.create' => array(
42 * 'email' => 'amy@example.com',
43 * 'location_type_id' => 123,
44 * ),
45 * ));
46 * @endcode
47 *
48 * The ChainSubscriber looks for any parameters of the form "api.Email.create";
49 * if found, it issues the nested API call (and passes some extra context --
50 * eg Amy's contact_id).
51 */
52 class ChainSubscriber implements EventSubscriberInterface {
53
54 /**
55 * @return array
56 */
57 public static function getSubscribedEvents() {
58 return [
59 Events::RESPOND => ['onApiRespond', Events::W_EARLY],
60 ];
61 }
62
63 /**
64 * @param \Civi\API\Event\RespondEvent $event
65 * API response event.
66 *
67 * @throws \Exception
68 */
69 public function onApiRespond(\Civi\API\Event\RespondEvent $event) {
70 $apiRequest = $event->getApiRequest();
71 if ($apiRequest['version'] < 4) {
72 $result = $event->getResponse();
73 if (\CRM_Utils_Array::value('is_error', $result, 0) == 0) {
74 $this->callNestedApi($event->getApiKernel(), $apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
75 $event->setResponse($result);
76 }
77 }
78 }
79
80 /**
81 * Call any nested api calls.
82 *
83 * TODO: We don't really need this to be a separate function.
84 * @param \Civi\API\Kernel $apiKernel
85 * @param $params
86 * @param $result
87 * @param $action
88 * @param $entity
89 * @param $version
90 * @throws \Exception
91 */
92 protected function callNestedApi($apiKernel, &$params, &$result, $action, $entity, $version) {
93 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
94
95 // We don't need to worry about nested api in the getfields/getoptions
96 // actions, so just return immediately.
97 if (in_array($action, ['getfields', 'getfield', 'getoptions'])) {
98 return;
99 }
100
101 if ($action == 'getsingle') {
102 // I don't understand the protocol here, but we don't want
103 // $result to be a recursive array
104 // $result['values'][0] = $result;
105 $oldResult = $result;
106 $result = ['values' => [0 => $oldResult]];
107 }
108 foreach ($params as $field => $newparams) {
109 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
110
111 // 'api.participant.delete' => 1 is a valid options - handle 1
112 // instead of an array
113 if ($newparams === 1) {
114 $newparams = ['version' => $version];
115 }
116 // can be api_ or api.
117 $separator = $field[3];
118 if (!($separator == '.' || $separator == '_')) {
119 continue;
120 }
121 $subAPI = explode($separator, $field);
122
123 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
124 $subParams = [
125 'debug' => \CRM_Utils_Array::value('debug', $params),
126 ];
127 $subEntity = _civicrm_api_get_entity_name_from_camel($subAPI[1]);
128
129 // Hard coded list of entitys that have fields starting api_ and shouldn't be automatically
130 // deemed to be chained API calls
131 $skipList = [
132 'SmsProvider' => ['type', 'url', 'params'],
133 'Job' => ['prefix', 'entity', 'action'],
134 'Contact' => ['key'],
135 ];
136 if (isset($skipList[$entity]) && in_array($subEntity, $skipList[$entity])) {
137 continue;
138 }
139
140 foreach ($result['values'] as $idIndex => $parentAPIValues) {
141
142 if ($subEntity != 'contact') {
143 //contact spits the dummy at activity_id so what else won't it like?
144 //set entity_id & entity table based on the parent's id & entity.
145 //e.g for something like note if the parent call is contact
146 //'entity_table' will be set to 'contact' & 'id' to the contact id
147 //from the parent call. in this case 'contact_id' will also be
148 //set to the parent's id
149 if (!($subEntity == 'line_item' && $lowercase_entity == 'contribution' && $action != 'create')) {
150 $subParams["entity_id"] = $parentAPIValues['id'];
151 $subParams['entity_table'] = 'civicrm_' . $lowercase_entity;
152 }
153
154 $addEntityId = TRUE;
155 if ($subEntity == 'relationship' && $lowercase_entity == 'contact') {
156 // if a relationship call is chained to a contact call, we need
157 // to check whether contact_id_a or contact_id_b for the
158 // relationship is given. If so, don't add an extra subParam
159 // "contact_id" => parent_id.
160 // See CRM-16084.
161 foreach (array_keys($newparams) as $key) {
162 if (substr($key, 0, 11) == 'contact_id_') {
163 $addEntityId = FALSE;
164 break;
165 }
166 }
167 }
168 if ($addEntityId) {
169 $subParams[$lowercase_entity . "_id"] = $parentAPIValues['id'];
170 }
171 }
172 if ($entity != 'Contact' && \CRM_Utils_Array::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
173 //e.g. if event_id is in the values returned & subentity is event
174 //then pass in event_id as 'id' don't do this for contact as it
175 //does some weird things like returning primary email &
176 //thus limiting the ability to chain email
177 //TODO - this might need the camel treatment
178 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
179 }
180
181 if (\CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
182 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
183 }
184 // if we are dealing with the same entity pass 'id' through
185 // (useful for get + delete for example)
186 if ($lowercase_entity == $subEntity) {
187 $subParams['id'] = $result['values'][$idIndex]['id'];
188 }
189
190 $subParams['version'] = $version;
191 if (!empty($params['check_permissions'])) {
192 $subParams['check_permissions'] = $params['check_permissions'];
193 }
194 $subParams['sequential'] = 1;
195 $subParams['api.has_parent'] = 1;
196 if (array_key_exists(0, $newparams)) {
197 $genericParams = $subParams;
198 // it is a numerically indexed array - ie. multiple creates
199 foreach ($newparams as $entityparams) {
200 $subParams = array_merge($genericParams, $entityparams);
201 _civicrm_api_replace_variables($subParams, $result['values'][$idIndex], $separator);
202 $result['values'][$idIndex][$field][] = $apiKernel->run($subEntity, $subaction, $subParams);
203 if ($result['is_error'] === 1) {
204 throw new \Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
205 }
206 }
207 }
208 else {
209
210 $subParams = array_merge($subParams, $newparams);
211 _civicrm_api_replace_variables($subParams, $result['values'][$idIndex], $separator);
212 $result['values'][$idIndex][$field] = $apiKernel->run($subEntity, $subaction, $subParams);
213 if (!empty($result['is_error'])) {
214 throw new \Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
215 }
216 }
217 }
218 }
219 }
220 if ($action == 'getsingle') {
221 $result = $result['values'][0];
222 }
223 }
224
225 }