Merge branch '4.6' of https://github.com/civicrm/civicrm-core
[civicrm-core.git] / Civi / API / Subscriber / ChainSubscriber.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 * @return array
55 */
56 public static function getSubscribedEvents() {
57 return array(
58 Events::RESPOND => array('onApiRespond', Events::W_EARLY),
59 );
60 }
61
62 /**
63 * @param \Civi\API\Event\RespondEvent $event
64 * API response event.
65 *
66 * @throws \Exception
67 */
68 public function onApiRespond(\Civi\API\Event\RespondEvent $event) {
69 $apiRequest = $event->getApiRequest();
70 $result = $event->getResponse();
71 if (\CRM_Utils_Array::value('is_error', $result, 0) == 0) {
72 $this->callNestedApi($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
73 $event->setResponse($result);
74 }
75 }
76
77 /**
78 * Call any nested api calls.
79 *
80 * TODO: We don't really need this to be a separate function.
81 * @param $params
82 * @param $result
83 * @param $action
84 * @param $entity
85 * @param $version
86 * @throws \Exception
87 */
88 protected function callNestedApi(&$params, &$result, $action, $entity, $version) {
89 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
90
91 // We don't need to worry about nested api in the getfields/getoptions
92 // actions, so just return immediately.
93 if (in_array($action, array('getfields', 'getfield', 'getoptions'))) {
94 return;
95 }
96
97 if ($action == 'getsingle') {
98 // I don't understand the protocol here, but we don't want
99 // $result to be a recursive array
100 // $result['values'][0] = $result;
101 $oldResult = $result;
102 $result = array('values' => array(0 => $oldResult));
103 }
104 foreach ($params as $field => $newparams) {
105 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
106
107 // 'api.participant.delete' => 1 is a valid options - handle 1
108 // instead of an array
109 if ($newparams === 1) {
110 $newparams = array('version' => $version);
111 }
112 // can be api_ or api.
113 $separator = $field[3];
114 if (!($separator == '.' || $separator == '_')) {
115 continue;
116 }
117 $subAPI = explode($separator, $field);
118
119 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
120 $subParams = array(
121 'debug' => \CRM_Utils_Array::value('debug', $params),
122 );
123 $subEntity = _civicrm_api_get_entity_name_from_camel($subAPI[1]);
124
125 foreach ($result['values'] as $idIndex => $parentAPIValues) {
126
127 if ($subEntity != 'contact') {
128 //contact spits the dummy at activity_id so what else won't it like?
129 //set entity_id & entity table based on the parent's id & entity.
130 //e.g for something like note if the parent call is contact
131 //'entity_table' will be set to 'contact' & 'id' to the contact id
132 //from the parent call. in this case 'contact_id' will also be
133 //set to the parent's id
134 $subParams["entity_id"] = $parentAPIValues['id'];
135 $subParams['entity_table'] = 'civicrm_' . $lowercase_entity;
136
137 $crm16084 = FALSE;
138 if ($subEntity == 'relationship' && $lowercase_entity == 'contact') {
139 // if a relationship call is chained to a contact call, we need
140 // to check whether contact_id_a or contact_id_b for the
141 // relationship is given. If so, don't add an extra subParam
142 // "contact_id" => parent_id.
143 // See CRM-16084.
144 foreach (array_keys($newparams) as $key) {
145 if (substr($key, 0, 11) == 'contact_id_') {
146 $crm16084 = TRUE;
147 break;
148 }
149 }
150 }
151 if (!$crm16084) {
152 $subParams[$lowercase_entity . "_id"] = $parentAPIValues['id'];
153 }
154 }
155 if ($entity != 'Contact' && \CRM_Utils_Array::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
156 //e.g. if event_id is in the values returned & subentity is event
157 //then pass in event_id as 'id' don't do this for contact as it
158 //does some weird things like returning primary email &
159 //thus limiting the ability to chain email
160 //TODO - this might need the camel treatment
161 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
162 }
163
164 if (\CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
165 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
166 }
167 // if we are dealing with the same entity pass 'id' through
168 // (useful for get + delete for example)
169 if ($lowercase_entity == $subEntity) {
170 $subParams['id'] = $result['values'][$idIndex]['id'];
171 }
172
173 $subParams['version'] = $version;
174 if (!empty($params['check_permissions'])) {
175 $subParams['check_permissions'] = $params['check_permissions'];
176 }
177 $subParams['sequential'] = 1;
178 $subParams['api.has_parent'] = 1;
179 if (array_key_exists(0, $newparams)) {
180 $genericParams = $subParams;
181 // it is a numerically indexed array - ie. multiple creates
182 foreach ($newparams as $entityparams) {
183 $subParams = array_merge($genericParams, $entityparams);
184 _civicrm_api_replace_variables($subParams, $result['values'][$idIndex], $separator);
185 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
186 if ($result['is_error'] === 1) {
187 throw new \Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
188 }
189 }
190 }
191 else {
192
193 $subParams = array_merge($subParams, $newparams);
194 _civicrm_api_replace_variables($subParams, $result['values'][$idIndex], $separator);
195 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
196 if (!empty($result['is_error'])) {
197 throw new \Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
198 }
199 }
200 }
201 }
202 }
203 if ($action == 'getsingle') {
204 $result = $result['values'][0];
205 }
206 }
207
208 }