Merge pull request #16008 from civicrm/5.20
[civicrm-core.git] / api / v3 / Membership.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
a30c801b 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
a30c801b
TO
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 |
6a488035
TO
9 +--------------------------------------------------------------------+
10 */
11
12/**
13 *
244bbdd8 14 * This api exposes CiviCRM membership contact records.
6a488035
TO
15 *
16 * @package CiviCRM_APIv3
6a488035
TO
17 */
18
ed4cc29d
JT
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 */
27function _civicrm_api3_membership_delete_spec(&$params) {
cf8f0fff 28 $params['preserve_contribution'] = [
9a47d762
JT
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,
cf8f0fff 33 ];
ed4cc29d
JT
34}
35
6a488035 36/**
244bbdd8 37 * Deletes an existing contact Membership.
6a488035 38 *
16b10e64 39 * @param array $params
cf470720 40 * Array array holding id - Id of the contact membership to be deleted.
8089541a 41 * @return array API result array.
8089541a 42 * @throws API_Exception
6a488035
TO
43 */
44function civicrm_api3_membership_delete($params) {
bbdc6c8b 45 if (isset($params['preserve_contribution'])) {
ed4cc29d
JT
46 if (CRM_Member_BAO_Membership::del($params['id'], $params['preserve_contribution'])) {
47 return civicrm_api3_create_success(TRUE, $params);
48 }
49 else {
77043bee 50 throw new API_Exception(ts('Could not delete membership'));
ed4cc29d
JT
51 }
52 }
53 else {
54 return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
55 }
6a488035
TO
56}
57
6a488035 58/**
dc64d047 59 * Create a Contact Membership.
6a488035
TO
60 *
61 * This API is used for creating a Membership for a contact.
62 * Required parameters : membership_type_id and status_id.
63 *
cf470720 64 * @param array $params
1747ab99 65 * Array of name/value property values of civicrm_membership.
6a488035 66 *
a6c01b45 67 * @return array
1747ab99 68 * API result array.
6a488035
TO
69 */
70function civicrm_api3_membership_create($params) {
6a488035 71 // check params for membership id during update
4d63cfde 72 if (!empty($params['id']) && !isset($params['skipStatusCal'])) {
5e4f7f74
EM
73 // Don't calculate status on existing membership - expect API use to pass them in
74 // or leave unchanged.
6a488035
TO
75 $params['skipStatusCal'] = 1;
76 }
77 else {
78 // also check for status id if override is set (during add/update)
4d63cfde 79 if (!empty($params['is_override']) && empty($params['status_id'])) {
6a488035
TO
80 return civicrm_api3_create_error('Status ID required');
81 }
82 }
83
cf8f0fff 84 $values = [];
6a488035
TO
85 _civicrm_api3_custom_format_params($params, $values, 'Membership');
86 $params = array_merge($params, $values);
87
fd88af0b 88 // Calculate membership dates
8f3aca71
CW
89 // Fixme: This code belongs in the BAO
90 if (empty($params['id']) || !empty($params['num_terms'])) {
fd88af0b 91 // If this is a new membership or we have a specified number of terms calculate membership dates.
8f3aca71 92 if (empty($params['id'])) {
fd88af0b 93 // This is a new membership, calculate the membership dates.
8f3aca71
CW
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 {
fd88af0b 103 // This is an existing membership, calculate the membership dates after renewal
7365dd7f
AP
104 // num_terms is treated as a 'special sauce' for is_renewal but this
105 // isn't really helpful for completing pendings.
8f3aca71
CW
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 }
cf8f0fff 113 foreach (['join_date', 'start_date', 'end_date'] as $date) {
8f3aca71
CW
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
f57cb50c 121 $ids = [];
fd88af0b
MW
122 if (empty($params['id'])) {
123 $params['action'] = CRM_Core_Action::ADD;
124 // we need user id during add mode
fd88af0b
MW
125 if (!empty($params['contact_id'])) {
126 $ids['userId'] = $params['contact_id'];
127 }
7c550ca0 128 }
fd88af0b
MW
129 else {
130 // edit mode
131 $params['action'] = CRM_Core_Action::UPDATE;
f57cb50c 132 // @todo remove $ids['membership'] is required in CRM_Price_BAO_LineItem::processPriceSet
4d63cfde 133 $ids['membership'] = $params['id'];
6a488035 134 }
6a488035 135
f57cb50c 136 // @todo stop passing $ids (membership and userId may be set above)
6a488035
TO
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
cf8f0fff 145 $membership = [];
6a488035
TO
146 _civicrm_api3_object_to_array($membershipBAO, $membership[$membershipBAO->id]);
147
244bbdd8 148 return civicrm_api3_create_success($membership, $params, 'Membership', 'create', $membershipBAO);
6a488035
TO
149
150}
11e09c59
TO
151
152/**
0aa0303c
EM
153 * Adjust Metadata for Create action.
154 *
155 * The metadata is used for setting defaults, documentation & validation.
6a488035 156 *
cf470720 157 * @param array $params
b081365f 158 * Array of parameters determined by getfields.
6a488035
TO
159 */
160function _civicrm_api3_membership_create_spec(&$params) {
161 $params['contact_id']['api.required'] = 1;
4d63cfde 162 $params['membership_type_id']['api.required'] = 1;
8f3aca71 163 $params['is_test']['api.default'] = 0;
cf8f0fff
CW
164 $params['membership_type_id']['api.aliases'] = ['membership_type'];
165 $params['status_id']['api.aliases'] = ['membership_status'];
166 $params['skipStatusCal'] = [
b2ed8e73
CW
167 'title' => 'Skip status calculation',
168 'description' => 'By default this is 0 if id is not set and 1 if it is set.',
d142432b 169 'type' => CRM_Utils_Type::T_BOOLEAN,
cf8f0fff
CW
170 ];
171 $params['num_terms'] = [
b2ed8e73
CW
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.',
68115618 174 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 175 ];
6a488035 176}
5e4f7f74 177
4d63cfde 178/**
dc64d047 179 * Adjust Metadata for Get action.
4d63cfde 180 *
0aa0303c
EM
181 * The metadata is used for setting defaults, documentation & validation.
182 *
cf470720 183 * @param array $params
b081365f 184 * Array of parameters determined by getfields.
4d63cfde
CW
185 */
186function _civicrm_api3_membership_get_spec(&$params) {
cf8f0fff
CW
187 $params['membership_type_id']['api.aliases'] = ['membership_type'];
188 $params['active_only'] = [
b2ed8e73
CW
189 'title' => 'Active Only',
190 'description' => 'Only retrieve active memberships',
5e4f7f74 191 'type' => CRM_Utils_Type::T_BOOLEAN,
cf8f0fff 192 ];
4d63cfde
CW
193}
194
6a488035 195/**
244bbdd8 196 * Get contact Membership record.
6a488035
TO
197 *
198 * This api will return the membership records for the contacts
199 * having membership based on the relationship with the direct members.
200 *
2241036a 201 * @param array $params
cf470720 202 * Key/value pairs for contact_id and some.
6a488035
TO
203 * options affecting the desired results; has legacy support
204 * for just passing the contact_id itself as the argument
205 *
16b10e64
CW
206 * @return array
207 * Array of all found membership property values.
6a488035
TO
208 */
209function civicrm_api3_membership_get($params) {
4d63cfde 210 $activeOnly = $membershipTypeId = $membershipType = NULL;
6a488035
TO
211
212 $contactID = CRM_Utils_Array::value('contact_id', $params);
a73daeff
E
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']);
6a488035
TO
216 }
217 $activeOnly = CRM_Utils_Array::value('active_only', $params, $activeOnly);
d031c654 218 if ($activeOnly && empty($params['status_id'])) {
cf8f0fff 219 $params['status_id'] = ['IN' => CRM_Member_BAO_MembershipStatus::getMembershipStatusCurrent()];
324116ad
SD
220 }
221
244bbdd8 222 $options = _civicrm_api3_get_options_from_params($params, TRUE, 'Membership', 'get');
d031c654 223 if ($options['is_count']) {
a73daeff 224 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
6a488035 225 }
9af2925b 226 $membershipValues = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Membership');
6a488035 227
37eda84b 228 $return = $options['return'];
22e263ad 229 if (empty($membershipValues) ||
37eda84b 230 (!empty($return)
231 && !array_key_exists('related_contact_id', $return)
232 && !array_key_exists('relationship_name', $return)
233 )
234 ) {
244bbdd8 235 return civicrm_api3_create_success($membershipValues, $params, 'Membership', 'get');
6a488035
TO
236 }
237
7c550ca0 238 $members = _civicrm_api3_membership_relationsship_get_customv2behaviour($params, $membershipValues, $contactID);
244bbdd8 239 return civicrm_api3_create_success($members, $params, 'Membership', 'get');
37eda84b 240}
241
242/**
dc64d047
EM
243 * Perform api v2 custom behaviour.
244 *
37eda84b 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 *
cf470720
TO
251 * @param array $params
252 * Parameters passed into get function.
100fef9d 253 * @param int $membershipTypeId
46332f2b
EM
254 * @param $activeOnly
255 *
a6c01b45 256 * @return array
72b3a70c 257 * result for calling function
37eda84b 258 */
259function _civicrm_api3_membership_get_customv2behaviour(&$params, $membershipTypeId, $activeOnly) {
260 // get the membership for the given contact ID
cf8f0fff 261 $membershipParams = ['contact_id' => $params['contact_id']];
37eda84b 262 if ($membershipTypeId) {
263 $membershipParams['membership_type_id'] = $membershipTypeId;
264 }
cf8f0fff 265 $membershipValues = [];
37eda84b 266 CRM_Member_BAO_Membership::getValues($membershipParams, $membershipValues, $activeOnly);
267 return $membershipValues;
268}
269
37eda84b 270/**
1747ab99 271 * Non-standard behaviour inherited from v2.
46332f2b 272 *
cf470720
TO
273 * @param array $params
274 * Parameters passed into get function.
46332f2b 275 * @param $membershipValues
100fef9d 276 * @param int $contactID
46332f2b 277 *
a6c01b45 278 * @return array
72b3a70c 279 * result for calling function
46332f2b 280 */
37eda84b 281function _civicrm_api3_membership_relationsship_get_customv2behaviour(&$params, $membershipValues, $contactID) {
cf8f0fff 282 $relationships = [];
6a488035
TO
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
a7488080 289 if (!empty($membershipType['relationship_type_id'])) {
6a488035
TO
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
e9ff5391 300 _civicrm_api3_custom_data_get($membershipValues[$membershipId], CRM_Utils_Array::value('check_permissions', $params), 'Membership', $membershipId, NULL, $values['membership_type_id']);
6a488035
TO
301 }
302
303 $members = $membershipValues;
304
5e4f7f74 305 // Populating contacts in members array based on their relationship with direct members.
6a488035
TO
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 }
37eda84b 324 return $members;
6a488035 325}