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