Merge pull request #16008 from civicrm/5.20
[civicrm-core.git] / api / v3 / Membership.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * This api exposes CiviCRM membership contact records.
15 *
16 * @package CiviCRM_APIv3
17 */
18
19 /**
20 * Adjust Metadata for Delete action.
21 *
22 * The metadata is used for setting defaults, documentation & validation.
23 *
24 * @param array $params
25 * Array of parameters determined by getfields.
26 */
27 function _civicrm_api3_membership_delete_spec(&$params) {
28 $params['preserve_contribution'] = [
29 'api.required' => 0,
30 'title' => 'Preserve Contribution',
31 'description' => 'By default this is 0, or 0 if not set. Set to 1 to preserve the associated contribution record when membership is deleted.',
32 'type' => CRM_Utils_Type::T_BOOLEAN,
33 ];
34 }
35
36 /**
37 * Deletes an existing contact Membership.
38 *
39 * @param array $params
40 * Array array holding id - Id of the contact membership to be deleted.
41 * @return array API result array.
42 * @throws API_Exception
43 */
44 function civicrm_api3_membership_delete($params) {
45 if (isset($params['preserve_contribution'])) {
46 if (CRM_Member_BAO_Membership::del($params['id'], $params['preserve_contribution'])) {
47 return civicrm_api3_create_success(TRUE, $params);
48 }
49 else {
50 throw new API_Exception(ts('Could not delete membership'));
51 }
52 }
53 else {
54 return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
55 }
56 }
57
58 /**
59 * Create a Contact Membership.
60 *
61 * This API is used for creating a Membership for a contact.
62 * Required parameters : membership_type_id and status_id.
63 *
64 * @param array $params
65 * Array of name/value property values of civicrm_membership.
66 *
67 * @return array
68 * API result array.
69 */
70 function civicrm_api3_membership_create($params) {
71 // check params for membership id during update
72 if (!empty($params['id']) && !isset($params['skipStatusCal'])) {
73 // Don't calculate status on existing membership - expect API use to pass them in
74 // or leave unchanged.
75 $params['skipStatusCal'] = 1;
76 }
77 else {
78 // also check for status id if override is set (during add/update)
79 if (!empty($params['is_override']) && empty($params['status_id'])) {
80 return civicrm_api3_create_error('Status ID required');
81 }
82 }
83
84 $values = [];
85 _civicrm_api3_custom_format_params($params, $values, 'Membership');
86 $params = array_merge($params, $values);
87
88 // Calculate membership dates
89 // Fixme: This code belongs in the BAO
90 if (empty($params['id']) || !empty($params['num_terms'])) {
91 // If this is a new membership or we have a specified number of terms calculate membership dates.
92 if (empty($params['id'])) {
93 // This is a new membership, calculate the membership dates.
94 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType(
95 $params['membership_type_id'],
96 CRM_Utils_Array::value('join_date', $params),
97 CRM_Utils_Array::value('start_date', $params),
98 CRM_Utils_Array::value('end_date', $params),
99 CRM_Utils_Array::value('num_terms', $params, 1)
100 );
101 }
102 else {
103 // This is an existing membership, calculate the membership dates after renewal
104 // num_terms is treated as a 'special sauce' for is_renewal but this
105 // isn't really helpful for completing pendings.
106 $calcDates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType(
107 $params['id'],
108 NULL,
109 CRM_Utils_Array::value('membership_type_id', $params),
110 $params['num_terms']
111 );
112 }
113 foreach (['join_date', 'start_date', 'end_date'] as $date) {
114 if (empty($params[$date]) && isset($calcDates[$date])) {
115 $params[$date] = $calcDates[$date];
116 }
117 }
118 }
119
120 // Fixme: This code belongs in the BAO
121 $ids = [];
122 if (empty($params['id'])) {
123 $params['action'] = CRM_Core_Action::ADD;
124 // we need user id during add mode
125 if (!empty($params['contact_id'])) {
126 $ids['userId'] = $params['contact_id'];
127 }
128 }
129 else {
130 // edit mode
131 $params['action'] = CRM_Core_Action::UPDATE;
132 // @todo remove $ids['membership'] is required in CRM_Price_BAO_LineItem::processPriceSet
133 $ids['membership'] = $params['id'];
134 }
135
136 // @todo stop passing $ids (membership and userId may be set above)
137 $membershipBAO = CRM_Member_BAO_Membership::create($params, $ids, TRUE);
138
139 if (array_key_exists('is_error', $membershipBAO)) {
140 // In case of no valid status for given dates, $membershipBAO
141 // is going to contain 'is_error' => "Error Message"
142 return civicrm_api3_create_error(ts('The membership can not be saved, no valid membership status for given dates'));
143 }
144
145 $membership = [];
146 _civicrm_api3_object_to_array($membershipBAO, $membership[$membershipBAO->id]);
147
148 return civicrm_api3_create_success($membership, $params, 'Membership', 'create', $membershipBAO);
149
150 }
151
152 /**
153 * Adjust Metadata for Create action.
154 *
155 * The metadata is used for setting defaults, documentation & validation.
156 *
157 * @param array $params
158 * Array of parameters determined by getfields.
159 */
160 function _civicrm_api3_membership_create_spec(&$params) {
161 $params['contact_id']['api.required'] = 1;
162 $params['membership_type_id']['api.required'] = 1;
163 $params['is_test']['api.default'] = 0;
164 $params['membership_type_id']['api.aliases'] = ['membership_type'];
165 $params['status_id']['api.aliases'] = ['membership_status'];
166 $params['skipStatusCal'] = [
167 'title' => 'Skip status calculation',
168 'description' => 'By default this is 0 if id is not set and 1 if it is set.',
169 'type' => CRM_Utils_Type::T_BOOLEAN,
170 ];
171 $params['num_terms'] = [
172 'title' => 'Number of terms',
173 'description' => 'Terms to add/renew. If this parameter is passed, dates will be calculated automatically. If no id is passed (new membership) and no dates are given, num_terms will be assumed to be 1.',
174 'type' => CRM_Utils_Type::T_INT,
175 ];
176 }
177
178 /**
179 * Adjust Metadata for Get action.
180 *
181 * The metadata is used for setting defaults, documentation & validation.
182 *
183 * @param array $params
184 * Array of parameters determined by getfields.
185 */
186 function _civicrm_api3_membership_get_spec(&$params) {
187 $params['membership_type_id']['api.aliases'] = ['membership_type'];
188 $params['active_only'] = [
189 'title' => 'Active Only',
190 'description' => 'Only retrieve active memberships',
191 'type' => CRM_Utils_Type::T_BOOLEAN,
192 ];
193 }
194
195 /**
196 * Get contact Membership record.
197 *
198 * This api will return the membership records for the contacts
199 * having membership based on the relationship with the direct members.
200 *
201 * @param array $params
202 * Key/value pairs for contact_id and some.
203 * options affecting the desired results; has legacy support
204 * for just passing the contact_id itself as the argument
205 *
206 * @return array
207 * Array of all found membership property values.
208 */
209 function civicrm_api3_membership_get($params) {
210 $activeOnly = $membershipTypeId = $membershipType = NULL;
211
212 $contactID = CRM_Utils_Array::value('contact_id', $params);
213 if (!empty($params['filters']) && is_array($params['filters']) && isset($params['filters']['is_current'])) {
214 $activeOnly = $params['filters']['is_current'];
215 unset($params['filters']['is_current']);
216 }
217 $activeOnly = CRM_Utils_Array::value('active_only', $params, $activeOnly);
218 if ($activeOnly && empty($params['status_id'])) {
219 $params['status_id'] = ['IN' => CRM_Member_BAO_MembershipStatus::getMembershipStatusCurrent()];
220 }
221
222 $options = _civicrm_api3_get_options_from_params($params, TRUE, 'Membership', 'get');
223 if ($options['is_count']) {
224 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
225 }
226 $membershipValues = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Membership');
227
228 $return = $options['return'];
229 if (empty($membershipValues) ||
230 (!empty($return)
231 && !array_key_exists('related_contact_id', $return)
232 && !array_key_exists('relationship_name', $return)
233 )
234 ) {
235 return civicrm_api3_create_success($membershipValues, $params, 'Membership', 'get');
236 }
237
238 $members = _civicrm_api3_membership_relationsship_get_customv2behaviour($params, $membershipValues, $contactID);
239 return civicrm_api3_create_success($members, $params, 'Membership', 'get');
240 }
241
242 /**
243 * Perform api v2 custom behaviour.
244 *
245 * When we copied apiv3 from api v2 we brought across some custom behaviours - in the case of
246 * membership a complicated return array is constructed. The original
247 * behaviour made contact_id a required field. We still need to keep this for v3 when contact_id
248 * is passed in as part of the reasonable expectation developers have that we will keep the api
249 * as stable as possible
250 *
251 * @param array $params
252 * Parameters passed into get function.
253 * @param int $membershipTypeId
254 * @param $activeOnly
255 *
256 * @return array
257 * result for calling function
258 */
259 function _civicrm_api3_membership_get_customv2behaviour(&$params, $membershipTypeId, $activeOnly) {
260 // get the membership for the given contact ID
261 $membershipParams = ['contact_id' => $params['contact_id']];
262 if ($membershipTypeId) {
263 $membershipParams['membership_type_id'] = $membershipTypeId;
264 }
265 $membershipValues = [];
266 CRM_Member_BAO_Membership::getValues($membershipParams, $membershipValues, $activeOnly);
267 return $membershipValues;
268 }
269
270 /**
271 * Non-standard behaviour inherited from v2.
272 *
273 * @param array $params
274 * Parameters passed into get function.
275 * @param $membershipValues
276 * @param int $contactID
277 *
278 * @return array
279 * result for calling function
280 */
281 function _civicrm_api3_membership_relationsship_get_customv2behaviour(&$params, $membershipValues, $contactID) {
282 $relationships = [];
283 foreach ($membershipValues as $membershipId => $values) {
284 // populate the membership type name for the membership type id
285 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']);
286
287 $membershipValues[$membershipId]['membership_name'] = $membershipType['name'];
288
289 if (!empty($membershipType['relationship_type_id'])) {
290 $relationships[$membershipType['relationship_type_id']] = $membershipId;
291 }
292
293 // populating relationship type name.
294 $relationshipType = new CRM_Contact_BAO_RelationshipType();
295 $relationshipType->id = CRM_Utils_Array::value('relationship_type_id', $membershipType);
296 if ($relationshipType->find(TRUE)) {
297 $membershipValues[$membershipId]['relationship_name'] = $relationshipType->name_a_b;
298 }
299
300 _civicrm_api3_custom_data_get($membershipValues[$membershipId], CRM_Utils_Array::value('check_permissions', $params), 'Membership', $membershipId, NULL, $values['membership_type_id']);
301 }
302
303 $members = $membershipValues;
304
305 // Populating contacts in members array based on their relationship with direct members.
306 if (!empty($relationships)) {
307 foreach ($relationships as $relTypeId => $membershipId) {
308 // As members are not direct members, there should not be
309 // membership id in the result array.
310 unset($membershipValues[$membershipId]['id']);
311 $relationship = new CRM_Contact_BAO_Relationship();
312 $relationship->contact_id_b = $contactID;
313 $relationship->relationship_type_id = $relTypeId;
314 if ($relationship->find()) {
315 while ($relationship->fetch()) {
316 clone($relationship);
317 $membershipValues[$membershipId]['contact_id'] = $relationship->contact_id_a;
318 $members[$membershipId]['related_contact_id'] = $relationship->contact_id_a;
319 }
320 }
321
322 }
323 }
324 return $members;
325 }