Merge pull request #14252 from jitendrapurohit/core-961
[civicrm-core.git] / Civi / API / Subscriber / ChainSubscriber.php
CommitLineData
0a946de2
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
0a946de2 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
0a946de2
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
0a946de2
TO
27
28namespace Civi\API\Subscriber;
46bcf597 29
0a946de2
TO
30use Civi\API\Events;
31use Symfony\Component\EventDispatcher\EventSubscriberInterface;
32
33/**
8882ff5c
TO
34 * The ChainSubscriber looks for API parameters which specify a nested or
35 * chained API call. For example:
0a946de2
TO
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 *
8882ff5c
TO
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).
0a946de2
TO
51 */
52class ChainSubscriber implements EventSubscriberInterface {
34f3bbd9 53
6550386a
EM
54 /**
55 * @return array
56 */
0a946de2 57 public static function getSubscribedEvents() {
c64f69d9
CW
58 return [
59 Events::RESPOND => ['onApiRespond', Events::W_EARLY],
60 ];
0a946de2
TO
61 }
62
6550386a
EM
63 /**
64 * @param \Civi\API\Event\RespondEvent $event
8882ff5c 65 * API response event.
6550386a
EM
66 *
67 * @throws \Exception
68 */
0a946de2
TO
69 public function onApiRespond(\Civi\API\Event\RespondEvent $event) {
70 $apiRequest = $event->getApiRequest();
8bcc0d86
CW
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 }
0a946de2
TO
77 }
78 }
79
80 /**
fe482240 81 * Call any nested api calls.
0a946de2
TO
82 *
83 * TODO: We don't really need this to be a separate function.
c0e26341 84 * @param \Civi\API\Kernel $apiKernel
257e7666
EM
85 * @param $params
86 * @param $result
87 * @param $action
88 * @param $entity
89 * @param $version
90 * @throws \Exception
0a946de2 91 */
c0e26341 92 protected function callNestedApi($apiKernel, &$params, &$result, $action, $entity, $version) {
4846df91 93 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
0a946de2 94
8882ff5c
TO
95 // We don't need to worry about nested api in the getfields/getoptions
96 // actions, so just return immediately.
c64f69d9 97 if (in_array($action, ['getfields', 'getfield', 'getoptions'])) {
0a946de2
TO
98 return;
99 }
100
4846df91 101 if ($action == 'getsingle') {
0a946de2
TO
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;
c64f69d9 106 $result = ['values' => [0 => $oldResult]];
0a946de2
TO
107 }
108 foreach ($params as $field => $newparams) {
109 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
110
8882ff5c
TO
111 // 'api.participant.delete' => 1 is a valid options - handle 1
112 // instead of an array
0a946de2 113 if ($newparams === 1) {
c64f69d9 114 $newparams = ['version' => $version];
0a946de2
TO
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];
c64f69d9 124 $subParams = [
0a946de2 125 'debug' => \CRM_Utils_Array::value('debug', $params),
c64f69d9 126 ];
4846df91 127 $subEntity = _civicrm_api_get_entity_name_from_camel($subAPI[1]);
0a946de2 128
449fbe14
SL
129 // Hard coded list of entitys that have fields starting api_ and shouldn't be automatically
130 // deemed to be chained API calls
c64f69d9
CW
131 $skipList = [
132 'SmsProvider' => ['type', 'url', 'params'],
133 'Job' => ['prefix', 'entity', 'action'],
134 'Contact' => ['key'],
135 ];
5bc7d8e2 136 if (isset($skipList[$entity]) && in_array($subEntity, $skipList[$entity])) {
449fbe14
SL
137 continue;
138 }
139
0a946de2
TO
140 foreach ($result['values'] as $idIndex => $parentAPIValues) {
141
4846df91 142 if ($subEntity != 'contact') {
0a946de2 143 //contact spits the dummy at activity_id so what else won't it like?
8882ff5c
TO
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
4a517906
PN
149 if (!($subEntity == 'line_item' && $lowercase_entity == 'contribution' && $action != 'create')) {
150 $subParams["entity_id"] = $parentAPIValues['id'];
151 $subParams['entity_table'] = 'civicrm_' . $lowercase_entity;
152 }
9960c0ef 153
602e7157 154 $addEntityId = TRUE;
9960c0ef
JV
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_') {
602e7157 163 $addEntityId = FALSE;
9960c0ef
JV
164 break;
165 }
166 }
167 }
602e7157 168 if ($addEntityId) {
9960c0ef
JV
169 $subParams[$lowercase_entity . "_id"] = $parentAPIValues['id'];
170 }
0a946de2 171 }
4846df91 172 if ($entity != 'Contact' && \CRM_Utils_Array::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
8882ff5c
TO
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
e4f46be0 175 //does some weird things like returning primary email &
0a946de2
TO
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 }
8882ff5c
TO
184 // if we are dealing with the same entity pass 'id' through
185 // (useful for get + delete for example)
4846df91 186 if ($lowercase_entity == $subEntity) {
0a946de2
TO
187 $subParams['id'] = $result['values'][$idIndex]['id'];
188 }
189
0a946de2
TO
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);
845d6d75 201 _civicrm_api_replace_variables($subParams, $result['values'][$idIndex], $separator);
7d572f56 202 $result['values'][$idIndex][$field][] = $apiKernel->run($subEntity, $subaction, $subParams);
0a946de2
TO
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);
845d6d75 211 _civicrm_api_replace_variables($subParams, $result['values'][$idIndex], $separator);
c0e26341 212 $result['values'][$idIndex][$field] = $apiKernel->run($subEntity, $subaction, $subParams);
0a946de2
TO
213 if (!empty($result['is_error'])) {
214 throw new \Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
215 }
216 }
217 }
218 }
219 }
4846df91 220 if ($action == 'getsingle') {
0a946de2
TO
221 $result = $result['values'][0];
222 }
223 }
224
6550386a 225}