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