Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
fee14197 | 4 | | CiviCRM version 5 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
6b83d5bd | 6 | | Copyright CiviCRM LLC (c) 2004-2019 | |
6a488035 TO |
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 | +--------------------------------------------------------------------+ | |
d25dd0ee | 26 | */ |
6a488035 TO |
27 | |
28 | /** | |
29 | * | |
30 | * @package CRM | |
6b83d5bd | 31 | * @copyright CiviCRM LLC (c) 2004-2019 |
6a488035 TO |
32 | */ |
33 | class CRM_Member_BAO_Membership extends CRM_Member_DAO_Membership { | |
34 | ||
35 | /** | |
fe482240 | 36 | * Static field for all the membership information that we can potentially import. |
6a488035 TO |
37 | * |
38 | * @var array | |
6a488035 TO |
39 | */ |
40 | static $_importableFields = NULL; | |
8ef12e64 | 41 | |
4e636a74 | 42 | static $_renewalActType = NULL; |
8ef12e64 | 43 | |
4e636a74 | 44 | static $_signupActType = NULL; |
8ef12e64 | 45 | |
bb3a214a | 46 | /** |
fe482240 | 47 | * Class constructor. |
bb3a214a | 48 | */ |
00be9182 | 49 | public function __construct() { |
6a488035 TO |
50 | parent::__construct(); |
51 | } | |
52 | ||
53 | /** | |
fe482240 | 54 | * Takes an associative array and creates a membership object. |
6a488035 TO |
55 | * |
56 | * the function extracts all the params it needs to initialize the created | |
57 | * membership object. The params array could contain additional unused name/value | |
58 | * pairs | |
59 | * | |
b2363ea8 TO |
60 | * @param array $params |
61 | * (reference ) an assoc array of name/value pairs. | |
62 | * @param array $ids | |
63 | * The array that holds all the db ids. | |
6a488035 | 64 | * |
16b10e64 | 65 | * @return CRM_Member_BAO_Membership |
6a488035 | 66 | */ |
00be9182 | 67 | public static function add(&$params, $ids = array()) { |
a5e2b32e | 68 | $oldStatus = $oldType = NULL; |
f880fd16 EM |
69 | $params['id'] = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('membership', $ids)); |
70 | if ($params['id']) { | |
71 | CRM_Utils_Hook::pre('edit', 'Membership', $params['id'], $params); | |
72 | } | |
73 | else { | |
1acc24d5 | 74 | CRM_Utils_Hook::pre('create', 'Membership', NULL, $params); |
f880fd16 EM |
75 | } |
76 | $id = $params['id']; | |
77 | // we do this after the hooks are called in case it has been altered | |
78 | if ($id) { | |
79 | $membershipObj = new CRM_Member_DAO_Membership(); | |
80 | $membershipObj->id = $id; | |
6a488035 TO |
81 | $membershipObj->find(); |
82 | while ($membershipObj->fetch()) { | |
83 | $oldStatus = $membershipObj->status_id; | |
84 | $oldType = $membershipObj->membership_type_id; | |
85 | } | |
86 | } | |
6a488035 TO |
87 | |
88 | if (array_key_exists('is_override', $params) && !$params['is_override']) { | |
89 | $params['is_override'] = 'null'; | |
90 | } | |
91 | ||
92 | $membership = new CRM_Member_BAO_Membership(); | |
93 | $membership->copyValues($params); | |
f880fd16 | 94 | $membership->id = $id; |
6a488035 TO |
95 | |
96 | $membership->save(); | |
97 | $membership->free(); | |
98 | ||
6a488035 TO |
99 | if (empty($membership->contact_id) || empty($membership->status_id)) { |
100 | // this means we are in renewal mode and are just updating the membership | |
101 | // record or this is an API update call and all fields are not present in the update record | |
b204fd50 | 102 | // however the hooks don't care and want all data CRM-7784 |
6a488035 TO |
103 | $tempMembership = new CRM_Member_DAO_Membership(); |
104 | $tempMembership->id = $membership->id; | |
105 | $tempMembership->find(TRUE); | |
106 | $membership = $tempMembership; | |
107 | } | |
108 | ||
109 | //get the log start date. | |
110 | //it is set during renewal of membership. | |
ca58d9b9 | 111 | $logStartDate = CRM_Utils_Array::value('log_start_date', $params); |
6a488035 | 112 | $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : CRM_Utils_Date::isoToMysql($membership->start_date); |
e0556ebe | 113 | $values = self::getStatusANDTypeValues($membership->id); |
6a488035 TO |
114 | |
115 | $membershipLog = array( | |
116 | 'membership_id' => $membership->id, | |
117 | 'status_id' => $membership->status_id, | |
118 | 'start_date' => $logStartDate, | |
119 | 'end_date' => CRM_Utils_Date::isoToMysql($membership->end_date), | |
120 | 'modified_date' => date('Ymd'), | |
121 | 'membership_type_id' => $values[$membership->id]['membership_type_id'], | |
122 | 'max_related' => $membership->max_related, | |
123 | ); | |
124 | ||
125 | $session = CRM_Core_Session::singleton(); | |
126 | // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id | |
127 | if ($session->get('userID')) { | |
128 | $membershipLog['modified_id'] = $session->get('userID'); | |
129 | } | |
130 | elseif (!empty($ids['userId'])) { | |
131 | $membershipLog['modified_id'] = $ids['userId']; | |
132 | } | |
133 | else { | |
134 | $membershipLog['modified_id'] = $membership->contact_id; | |
135 | } | |
136 | ||
4ed92e91 | 137 | CRM_Member_BAO_MembershipLog::add($membershipLog); |
6a488035 TO |
138 | |
139 | // reset the group contact cache since smart groups might be affected due to this | |
2b68a50c | 140 | CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush(); |
6a488035 | 141 | |
b6d493f3 | 142 | $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get'); |
66a1e31f MD |
143 | $activityParams = array( |
144 | 'status_id' => CRM_Utils_Array::value('membership_activity_status', $params, 'Completed'), | |
145 | ); | |
146 | if (in_array($allStatus[$membership->status_id], array('Pending', 'Grace'))) { | |
98f0683a | 147 | $activityParams['status_id'] = 'Scheduled'; |
b6d493f3 | 148 | } |
98f0683a | 149 | $activityParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']); |
b6d493f3 | 150 | |
d2460a89 MD |
151 | $targetContactID = $membership->contact_id; |
152 | if (!empty($params['is_for_organization'])) { | |
153 | $targetContactID = CRM_Utils_Array::value('userId', $ids); | |
154 | } | |
f880fd16 | 155 | if ($id) { |
6a488035 | 156 | if ($membership->status_id != $oldStatus) { |
d2460a89 MD |
157 | CRM_Activity_BAO_Activity::addActivity($membership, |
158 | 'Change Membership Status', | |
159 | NULL, | |
160 | array( | |
161 | 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}", | |
162 | 'source_contact_id' => $membershipLog['modified_id'], | |
66a1e31f | 163 | 'priority_id' => 'Normal', |
d2460a89 | 164 | ) |
6a488035 | 165 | ); |
6a488035 TO |
166 | } |
167 | if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) { | |
4d63cfde | 168 | $membershipTypes = CRM_Member_BAO_Membership::buildOptions('membership_type_id', 'get'); |
d2460a89 MD |
169 | CRM_Activity_BAO_Activity::addActivity($membership, |
170 | 'Change Membership Type', | |
171 | NULL, | |
172 | array( | |
173 | 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}", | |
174 | 'source_contact_id' => $membershipLog['modified_id'], | |
66a1e31f | 175 | 'priority_id' => 'Normal', |
d2460a89 | 176 | ) |
6a488035 | 177 | ); |
d2460a89 | 178 | } |
b6d493f3 MD |
179 | |
180 | foreach (array('Membership Signup', 'Membership Renewal') as $activityType) { | |
181 | $activityParams['id'] = CRM_Utils_Array::value('id', | |
182 | civicrm_api3('Activity', 'Get', | |
183 | array( | |
184 | 'source_record_id' => $membership->id, | |
185 | 'activity_type_id' => $activityType, | |
186 | 'status_id' => 'Scheduled', | |
187 | ) | |
188 | ) | |
189 | ); | |
190 | // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership | |
191 | // 2. OR Create renewal activity scheduled if its membership renewal will be paid later | |
c329a76a | 192 | if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) || $activityType == 'Membership Renewal')) { |
b6d493f3 MD |
193 | CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID, $activityParams); |
194 | break; | |
195 | } | |
6a488035 | 196 | } |
b6d493f3 | 197 | |
6a488035 TO |
198 | CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); |
199 | } | |
200 | else { | |
b6d493f3 | 201 | CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams); |
6a488035 TO |
202 | CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership); |
203 | } | |
204 | ||
205 | return $membership; | |
206 | } | |
207 | ||
208 | /** | |
7b835f7c | 209 | * Fetch the object and store the values in the values array. |
6a488035 | 210 | * |
b2363ea8 TO |
211 | * @param array $params |
212 | * Input parameters to find object. | |
213 | * @param array $values | |
214 | * Output values of the object. | |
215 | * @param bool $active | |
216 | * Do you want only active memberships to. | |
6a488035 | 217 | * be returned |
f1e48e7f | 218 | * @param bool $relatedMemberships |
7b835f7c EM |
219 | * |
220 | * @return CRM_Member_BAO_Membership|null | |
221 | * The found object or null | |
6a488035 | 222 | */ |
f1e48e7f | 223 | public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) { |
6a488035 TO |
224 | if (empty($params)) { |
225 | return NULL; | |
226 | } | |
227 | $membership = new CRM_Member_BAO_Membership(); | |
228 | ||
229 | $membership->copyValues($params); | |
230 | $membership->find(); | |
231 | $memberships = array(); | |
232 | while ($membership->fetch()) { | |
233 | if ($active && | |
234 | (!CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', | |
e0556ebe TO |
235 | $membership->status_id, |
236 | 'is_current_member' | |
237 | )) | |
6a488035 TO |
238 | ) { |
239 | continue; | |
240 | } | |
241 | ||
242 | CRM_Core_DAO::storeValues($membership, $values[$membership->id]); | |
243 | $memberships[$membership->id] = $membership; | |
f1e48e7f | 244 | if ($relatedMemberships && !empty($membership->owner_membership_id)) { |
245 | $values['owner_membership_ids'][] = $membership->owner_membership_id; | |
246 | } | |
6a488035 TO |
247 | } |
248 | ||
249 | return $memberships; | |
250 | } | |
251 | ||
252 | /** | |
fe482240 | 253 | * Takes an associative array and creates a membership object. |
6a488035 | 254 | * |
b2363ea8 TO |
255 | * @param array $params |
256 | * (reference ) an assoc array of name/value pairs. | |
257 | * @param array $ids | |
13a16f43 | 258 | * Deprecated parameter The array that holds all the db ids. |
8efea814 | 259 | * @param bool $skipRedirect |
8efea814 EM |
260 | * |
261 | * @throws CRM_Core_Exception | |
6a488035 | 262 | * |
906e6120 | 263 | * @return CRM_Member_BAO_Membership|CRM_Core_Error |
6a488035 | 264 | */ |
d2460a89 | 265 | public static function create(&$params, &$ids, $skipRedirect = FALSE) { |
6a488035 TO |
266 | // always calculate status if is_override/skipStatusCal is not true. |
267 | // giving respect to is_override during import. CRM-4012 | |
268 | ||
269 | // To skip status calculation we should use 'skipStatusCal'. | |
270 | // eg pay later membership, membership update cron CRM-3984 | |
271 | ||
8cc574cf | 272 | if (empty($params['is_override']) && empty($params['skipStatusCal'])) { |
0042ddd9 | 273 | $dates = array('start_date', 'end_date', 'join_date'); |
7b835f7c EM |
274 | // Declare these out of courtesy as IDEs don't pick up the setting of them below. |
275 | $start_date = $end_date = $join_date = NULL; | |
0042ddd9 | 276 | foreach ($dates as $date) { |
b5588874 | 277 | $$date = $params[$date] = CRM_Utils_Date::processDate(CRM_Utils_Array::value($date, $params), NULL, TRUE, 'Ymd'); |
6a488035 TO |
278 | } |
279 | ||
280 | //fix for CRM-3570, during import exclude the statuses those having is_admin = 1 | |
281 | $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE); | |
282 | ||
283 | //CRM-3724 always skip is_admin if is_override != true. | |
8cc574cf | 284 | if (!$excludeIsAdmin && empty($params['is_override'])) { |
6a488035 TO |
285 | $excludeIsAdmin = TRUE; |
286 | } | |
287 | ||
01f6b47e | 288 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($start_date, $end_date, $join_date, |
5f11bbcc | 289 | 'today', $excludeIsAdmin, CRM_Utils_Array::value('membership_type_id', $params), $params |
6a488035 TO |
290 | ); |
291 | if (empty($calcStatus)) { | |
dcc4f6a7 | 292 | // Redirect the form in case of error |
293 | // @todo this redirect in the BAO layer is really bad & should be moved to the form layer | |
294 | // however since we have no idea how (if) this is triggered we can't safely move / remove it | |
295 | // NB I tried really hard to trigger this error from backoffice membership form in order to test it | |
296 | // and am convinced form validation is complete on that form WRT this error. | |
297 | $errorParams = array( | |
298 | 'message_title' => ts('No valid membership status for given dates.'), | |
299 | 'legacy_redirect_path' => 'civicrm/contact/view', | |
300 | 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member", | |
301 | ); | |
e6b0848f | 302 | throw new CRM_Core_Exception(ts( |
303 | "The membership cannot be saved because the status cannot be calculated for start_date: $start_date end_date $end_date join_date $join_date as at " . date('Y-m-d H:i:s')), | |
304 | 0, | |
305 | $errorParams | |
306 | ); | |
6a488035 TO |
307 | } |
308 | $params['status_id'] = $calcStatus['id']; | |
309 | } | |
310 | ||
311 | // data cleanup only: all verifications on number of related memberships are done upstream in: | |
7b835f7c EM |
312 | // CRM_Member_BAO_Membership::createRelatedMemberships() |
313 | // CRM_Contact_BAO_Relationship::relatedMemberships() | |
039f3e71 | 314 | if (!empty($params['owner_membership_id'])) { |
6a488035 | 315 | unset($params['max_related']); |
8efea814 EM |
316 | } |
317 | else { | |
6a488035 TO |
318 | // if membership allows related, default max_related to value in membership_type |
319 | if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) { | |
320 | $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($params['membership_type_id']); | |
321 | if (isset($membershipType['relationship_type_id'])) { | |
322 | $params['max_related'] = CRM_Utils_Array::value('max_related', $membershipType); | |
323 | } | |
324 | } | |
325 | } | |
326 | ||
327 | $transaction = new CRM_Core_Transaction(); | |
328 | ||
329 | $membership = self::add($params, $ids); | |
330 | ||
331 | if (is_a($membership, 'CRM_Core_Error')) { | |
332 | $transaction->rollback(); | |
333 | return $membership; | |
334 | } | |
335 | ||
336 | // add custom field values | |
a7488080 | 337 | if (!empty($params['custom']) && is_array($params['custom']) |
6a488035 TO |
338 | ) { |
339 | CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id); | |
340 | } | |
341 | ||
342 | $params['membership_id'] = $membership->id; | |
343 | if (isset($ids['membership'])) { | |
344 | $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', | |
08fd4b45 | 345 | $membership->id, |
6a488035 TO |
346 | 'contribution_id', |
347 | 'membership_id' | |
348 | ); | |
349 | } | |
3c0201c9 | 350 | |
13a16f43 | 351 | // This code ensures a line item is created but it is recomended you pass in 'skipLineItem' or 'line_item' |
356bfcaf | 352 | if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) { |
353 | CRM_Price_BAO_LineItem::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']); | |
354 | } | |
d5b95619 | 355 | $params['skipLineItem'] = TRUE; |
3c0201c9 | 356 | |
6a488035 | 357 | //record contribution for this membership |
8cc574cf | 358 | if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) { |
8d8bd076 | 359 | $memInfo = array_merge($params, array('membership_id' => $membership->id)); |
360 | $params['contribution'] = self::recordMembershipContribution($memInfo, $ids); | |
6a488035 | 361 | } |
3c0201c9 | 362 | |
82cc6775 PN |
363 | if (!empty($params['lineItems'])) { |
364 | $params['line_item'] = $params['lineItems']; | |
365 | } | |
366 | ||
367 | //do cleanup line items if membership edit the Membership type. | |
368 | if (empty($ids['contribution']) && !empty($ids['membership'])) { | |
369 | CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership'); | |
370 | } | |
3c0201c9 | 371 | |
13a16f43 | 372 | // This could happen if there is no contribution or we are in one of many |
373 | // weird and wonderful flows. This is scary code. Keep adding tests. | |
82cc6775 | 374 | if (!empty($params['line_item']) && empty($ids['contribution'])) { |
13a16f43 | 375 | |
376 | foreach ($params['line_item'] as $priceSetId => $lineItems) { | |
377 | foreach ($lineItems as $lineIndex => $lineItem) { | |
378 | $lineMembershipType = CRM_Utils_Array::value('membership_type_id', $lineItem); | |
379 | if (CRM_Utils_Array::value('contribution', $params)) { | |
380 | $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id; | |
381 | } | |
382 | if ($lineMembershipType && $lineMembershipType == CRM_Utils_Array::value('membership_type_id', $params)) { | |
383 | $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id; | |
384 | $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership'; | |
385 | } | |
386 | elseif (!$lineMembershipType && CRM_Utils_Array::value('contribution', $params)) { | |
387 | $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id; | |
388 | $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution'; | |
389 | } | |
390 | } | |
391 | } | |
356bfcaf | 392 | CRM_Price_BAO_LineItem::processPriceSet( |
393 | $membership->id, | |
394 | $params['line_item'], | |
395 | CRM_Utils_Array::value('contribution', $params) | |
396 | ); | |
d5b95619 | 397 | } |
6a488035 TO |
398 | |
399 | //insert payment record for this membership | |
a7488080 | 400 | if (!empty($params['relate_contribution_id'])) { |
e0556ebe | 401 | CRM_Member_BAO_MembershipPayment::create(array( |
353ffa53 | 402 | 'membership_id' => $membership->id, |
67dbb78c | 403 | 'membership_type_id' => $membership->membership_type_id, |
353ffa53 TO |
404 | 'contribution_id' => $params['relate_contribution_id'], |
405 | )); | |
6a488035 TO |
406 | } |
407 | ||
6a488035 TO |
408 | $transaction->commit(); |
409 | ||
410 | self::createRelatedMemberships($params, $membership); | |
411 | ||
412 | // do not add to recent items for import, CRM-4399 | |
a7488080 | 413 | if (empty($params['skipRecentView'])) { |
6a488035 TO |
414 | $url = CRM_Utils_System::url('civicrm/contact/view/membership', |
415 | "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home" | |
416 | ); | |
7b835f7c EM |
417 | if (empty($membership->membership_type_id)) { |
418 | // ie in an update situation. | |
6a488035 TO |
419 | $membership->find(TRUE); |
420 | } | |
421 | $membershipTypes = CRM_Member_PseudoConstant::membershipType(); | |
422 | $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id]; | |
423 | ||
424 | $recentOther = array(); | |
425 | if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) { | |
426 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', | |
427 | "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home" | |
428 | ); | |
429 | } | |
430 | if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) { | |
431 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', | |
432 | "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home" | |
433 | ); | |
434 | } | |
435 | ||
436 | // add the recently created Membership | |
437 | CRM_Utils_Recent::add($title, | |
438 | $url, | |
439 | $membership->id, | |
440 | 'Membership', | |
441 | $membership->contact_id, | |
442 | NULL, | |
443 | $recentOther | |
444 | ); | |
445 | } | |
446 | ||
447 | return $membership; | |
448 | } | |
449 | ||
450 | /** | |
fe482240 | 451 | * Check the membership extended through relationship. |
6a488035 | 452 | * |
5c3a7abf AP |
453 | * @param int $membershipTypeID |
454 | * Membership type id. | |
b2363ea8 TO |
455 | * @param int $contactId |
456 | * Contact id. | |
ada8a833 | 457 | * |
b2363ea8 | 458 | * @param int $action |
6a488035 | 459 | * |
608e6658 | 460 | * @return array |
a6c01b45 | 461 | * array of contact_id of all related contacts. |
6a488035 | 462 | */ |
5c3a7abf | 463 | public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action::ADD) { |
6a488035 | 464 | $contacts = array(); |
6a488035 TO |
465 | |
466 | $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID); | |
467 | $relationships = array(); | |
468 | if (isset($membershipType['relationship_type_id'])) { | |
469 | $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, | |
470 | CRM_Contact_BAO_Relationship::CURRENT | |
471 | ); | |
472 | if ($action & CRM_Core_Action::UPDATE) { | |
473 | $pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId, | |
474 | CRM_Contact_BAO_Relationship::PAST | |
475 | ); | |
476 | $relationships = array_merge($relationships, $pastRelationships); | |
477 | } | |
478 | } | |
479 | ||
480 | if (!empty($relationships)) { | |
481 | // check for each contact relationships | |
482 | foreach ($relationships as $values) { | |
483 | //get details of the relationship type | |
484 | $relType = array('id' => $values['civicrm_relationship_type_id']); | |
485 | $relValues = array(); | |
486 | CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues); | |
487 | // Check if contact's relationship type exists in membership type | |
e0556ebe TO |
488 | $relTypeDirs = array(); |
489 | $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']); | |
6a488035 TO |
490 | $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']); |
491 | $bidirectional = FALSE; | |
492 | foreach ($relTypeIds as $key => $value) { | |
493 | $relTypeDirs[] = $value . '_' . $relDirections[$key]; | |
494 | if (in_array($value, $relType) && | |
495 | $relValues['name_a_b'] == $relValues['name_b_a'] | |
496 | ) { | |
497 | $bidirectional = TRUE; | |
498 | break; | |
499 | } | |
500 | } | |
501 | $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype']; | |
502 | if ($bidirectional || in_array($relTypeDir, $relTypeDirs)) { | |
503 | // $values['status'] is going to have value for | |
504 | // current or past relationships. | |
505 | $contacts[$values['cid']] = $values['status']; | |
506 | } | |
507 | } | |
508 | } | |
509 | ||
510 | // Sort by contact_id ascending | |
511 | ksort($contacts); | |
512 | return $contacts; | |
513 | } | |
514 | ||
515 | /** | |
fe482240 EM |
516 | * Retrieve DB object based on input parameters. |
517 | * | |
518 | * It also stores all the retrieved values in the default array. | |
6a488035 | 519 | * |
b2363ea8 TO |
520 | * @param array $params |
521 | * (reference ) an assoc array of name/value pairs. | |
522 | * @param array $defaults | |
523 | * (reference ) an assoc array to hold the name / value pairs. | |
6a488035 | 524 | * in a hierarchical manner |
8efea814 | 525 | * |
16b10e64 | 526 | * @return CRM_Member_BAO_Membership |
6a488035 | 527 | */ |
00be9182 | 528 | public static function retrieve(&$params, &$defaults) { |
6a488035 TO |
529 | $membership = new CRM_Member_DAO_Membership(); |
530 | ||
531 | $membership->copyValues($params); | |
532 | ||
533 | if ($membership->find(TRUE)) { | |
534 | CRM_Core_DAO::storeValues($membership, $defaults); | |
535 | ||
536 | //get the membership status and type values. | |
537 | $statusANDType = self::getStatusANDTypeValues($membership->id); | |
538 | foreach (array( | |
c5c263ca AH |
539 | 'status', |
540 | 'membership_type', | |
541 | ) as $fld) { | |
6a488035 TO |
542 | $defaults[$fld] = CRM_Utils_Array::value($fld, $statusANDType[$membership->id]); |
543 | } | |
a7488080 | 544 | if (!empty($statusANDType[$membership->id]['is_current_member'])) { |
6a488035 TO |
545 | $defaults['active'] = TRUE; |
546 | } | |
547 | ||
548 | $membership->free(); | |
549 | ||
550 | return $membership; | |
551 | } | |
552 | ||
553 | return NULL; | |
554 | } | |
555 | ||
556 | /** | |
7b835f7c | 557 | * Get membership status and membership type values. |
6a488035 | 558 | * |
b2363ea8 TO |
559 | * @param int $membershipId |
560 | * Membership id of values to return. | |
6a488035 | 561 | * |
a6c01b45 | 562 | * @return array |
16b10e64 | 563 | * Array of key value pairs |
6a488035 | 564 | */ |
00be9182 | 565 | public static function getStatusANDTypeValues($membershipId) { |
6a488035 TO |
566 | $values = array(); |
567 | if (!$membershipId) { | |
568 | return $values; | |
569 | } | |
570 | $sql = ' | |
571 | SELECT membership.id as id, | |
572 | status.id as status_id, | |
573 | status.label as status, | |
574 | status.is_current_member as is_current_member, | |
575 | type.id as membership_type_id, | |
576 | type.name as membership_type, | |
577 | type.relationship_type_id as relationship_type_id | |
578 | FROM civicrm_membership membership | |
579 | INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id ) | |
580 | INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id ) | |
581 | WHERE membership.id = %1'; | |
582 | $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($membershipId, 'Positive'))); | |
e0556ebe TO |
583 | $properties = array( |
584 | 'status', | |
585 | 'status_id', | |
586 | 'membership_type', | |
587 | 'membership_type_id', | |
588 | 'is_current_member', | |
21dfd5f5 | 589 | 'relationship_type_id', |
e0556ebe | 590 | ); |
6a488035 TO |
591 | while ($dao->fetch()) { |
592 | foreach ($properties as $property) { | |
593 | $values[$dao->id][$property] = $dao->$property; | |
594 | } | |
595 | } | |
596 | ||
597 | return $values; | |
598 | } | |
599 | ||
3506b6cd | 600 | /** |
100fef9d | 601 | * Delete membership. |
7b835f7c | 602 | * |
f5e53870 | 603 | * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent. |
3506b6cd | 604 | * |
b2363ea8 TO |
605 | * @param int $membershipId |
606 | * Membership id that needs to be deleted. | |
3506b6cd | 607 | * |
7b835f7c EM |
608 | * @return int |
609 | * Id of deleted Membership on success, false otherwise. | |
3506b6cd | 610 | */ |
086fea8e | 611 | public static function del($membershipId, $preserveContrib = FALSE) { |
3506b6cd DG |
612 | //delete related first and then delete parent. |
613 | self::deleteRelatedMemberships($membershipId); | |
ed4cc29d | 614 | return self::deleteMembership($membershipId, $preserveContrib); |
3506b6cd | 615 | } |
d824fb6e | 616 | |
6a488035 | 617 | /** |
100fef9d | 618 | * Delete membership. |
6a488035 | 619 | * |
b2363ea8 TO |
620 | * @param int $membershipId |
621 | * Membership id that needs to be deleted. | |
6a488035 | 622 | * |
7b835f7c EM |
623 | * @return int |
624 | * Id of deleted Membership on success, false otherwise. | |
6a488035 | 625 | */ |
086fea8e | 626 | public static function deleteMembership($membershipId, $preserveContrib = FALSE) { |
46d8f506 DL |
627 | // CRM-12147, retrieve membership data before we delete it for hooks |
628 | $params = array('id' => $membershipId); | |
629 | $memValues = array(); | |
630 | $memberships = self::getValues($params, $memValues); | |
3506b6cd | 631 | |
46d8f506 DL |
632 | $membership = $memberships[$membershipId]; |
633 | ||
634 | CRM_Utils_Hook::pre('delete', 'Membership', $membershipId, $memValues); | |
6a488035 TO |
635 | |
636 | $transaction = new CRM_Core_Transaction(); | |
637 | ||
638 | $results = NULL; | |
639 | //delete activity record | |
640 | $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); | |
641 | ||
642 | $params = array(); | |
e0556ebe TO |
643 | $deleteActivity = FALSE; |
644 | $membershipActivities = array( | |
46d8f506 DL |
645 | 'Membership Signup', |
646 | 'Membership Renewal', | |
647 | 'Change Membership Status', | |
648 | 'Change Membership Type', | |
21dfd5f5 | 649 | 'Membership Renewal Reminder', |
46d8f506 | 650 | ); |
e0556ebe | 651 | foreach ($membershipActivities as $membershipActivity) { |
6a488035 TO |
652 | $activityId = array_search($membershipActivity, $activityTypes); |
653 | if ($activityId) { | |
654 | $params['activity_type_id'][] = $activityId; | |
e0556ebe | 655 | $deleteActivity = TRUE; |
6a488035 TO |
656 | } |
657 | } | |
658 | if ($deleteActivity) { | |
659 | $params['source_record_id'] = $membershipId; | |
46d8f506 | 660 | CRM_Activity_BAO_Activity::deleteActivity($params); |
6a488035 | 661 | } |
ed4cc29d | 662 | self::deleteMembershipPayment($membershipId, $preserveContrib); |
6a488035 | 663 | |
d0fbc816 | 664 | $results = $membership->delete(); |
6a488035 TO |
665 | $transaction->commit(); |
666 | ||
667 | CRM_Utils_Hook::post('delete', 'Membership', $membership->id, $membership); | |
668 | ||
669 | // delete the recently created Membership | |
670 | $membershipRecent = array( | |
671 | 'id' => $membershipId, | |
672 | 'type' => 'Membership', | |
673 | ); | |
674 | CRM_Utils_Recent::del($membershipRecent); | |
675 | ||
676 | return $results; | |
677 | } | |
678 | ||
3506b6cd | 679 | /** |
fe482240 | 680 | * Delete related memberships. |
3506b6cd DG |
681 | * |
682 | * @param int $ownerMembershipId | |
683 | * @param int $contactId | |
684 | * | |
685 | * @return null | |
3506b6cd | 686 | */ |
00be9182 | 687 | public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) { |
3506b6cd | 688 | if (!$ownerMembershipId && !$contactId) { |
608e6658 | 689 | return FALSE; |
3506b6cd DG |
690 | } |
691 | ||
692 | $membership = new CRM_Member_DAO_Membership(); | |
693 | $membership->owner_membership_id = $ownerMembershipId; | |
694 | ||
695 | if ($contactId) { | |
696 | $membership->contact_id = $contactId; | |
697 | } | |
698 | ||
699 | $membership->find(); | |
700 | while ($membership->fetch()) { | |
701 | //delete related first and then delete parent. | |
702 | self::deleteRelatedMemberships($membership->id); | |
703 | self::deleteMembership($membership->id); | |
704 | } | |
705 | $membership->free(); | |
706 | } | |
707 | ||
6a488035 | 708 | /** |
100fef9d | 709 | * Obtain active/inactive memberships from the list of memberships passed to it. |
6a488035 | 710 | * |
b2363ea8 TO |
711 | * @param array $memberships |
712 | * Membership records. | |
713 | * @param string $status | |
714 | * Active or inactive. | |
6a488035 | 715 | * |
a6c01b45 CW |
716 | * @return array |
717 | * array of memberships based on status | |
6a488035 | 718 | */ |
00be9182 | 719 | public static function activeMembers($memberships, $status = 'active') { |
6a488035 TO |
720 | $actives = array(); |
721 | if ($status == 'active') { | |
722 | foreach ($memberships as $f => $v) { | |
a7488080 | 723 | if (!empty($v['active'])) { |
6a488035 TO |
724 | $actives[$f] = $v; |
725 | } | |
726 | } | |
727 | return $actives; | |
728 | } | |
729 | elseif ($status == 'inactive') { | |
730 | foreach ($memberships as $f => $v) { | |
a7488080 | 731 | if (empty($v['active'])) { |
6a488035 TO |
732 | $actives[$f] = $v; |
733 | } | |
734 | } | |
735 | return $actives; | |
736 | } | |
737 | return NULL; | |
738 | } | |
739 | ||
6a488035 | 740 | /** |
fe482240 | 741 | * Return Membership Block info in Contribution Pages. |
6a488035 | 742 | * |
b2363ea8 TO |
743 | * @param int $pageID |
744 | * Contribution page id. | |
e46e9a0b EM |
745 | * |
746 | * @return array|null | |
6a488035 | 747 | */ |
00be9182 | 748 | public static function getMembershipBlock($pageID) { |
e0556ebe TO |
749 | $membershipBlock = array(); |
750 | $dao = new CRM_Member_DAO_MembershipBlock(); | |
6a488035 TO |
751 | $dao->entity_table = 'civicrm_contribution_page'; |
752 | ||
753 | $dao->entity_id = $pageID; | |
754 | $dao->is_active = 1; | |
755 | if ($dao->find(TRUE)) { | |
756 | CRM_Core_DAO::storeValues($dao, $membershipBlock); | |
a7488080 | 757 | if (!empty($membershipBlock['membership_types'])) { |
6a488035 TO |
758 | $membershipTypes = unserialize($membershipBlock['membership_types']); |
759 | if (!is_array($membershipTypes)) { | |
760 | return $membershipBlock; | |
761 | } | |
762 | $memTypes = array(); | |
763 | foreach ($membershipTypes as $key => $value) { | |
764 | $membershipBlock['auto_renew'][$key] = $value; | |
765 | $memTypes[$key] = $key; | |
766 | } | |
767 | $membershipBlock['membership_types'] = implode(',', $memTypes); | |
768 | } | |
769 | } | |
770 | else { | |
771 | return NULL; | |
772 | } | |
773 | ||
774 | return $membershipBlock; | |
775 | } | |
776 | ||
777 | /** | |
fe482240 | 778 | * Return a current membership of given contact. |
7b835f7c | 779 | * |
c490a46a | 780 | * NB: if more than one membership meets criteria, a randomly selected one is returned. |
6a488035 | 781 | * |
b2363ea8 TO |
782 | * @param int $contactID |
783 | * Contact id. | |
784 | * @param int $memType | |
785 | * Membership type, null to retrieve all types. | |
6a488035 | 786 | * @param int $isTest |
b2363ea8 TO |
787 | * @param int $membershipId |
788 | * If provided, then determine if it is current. | |
789 | * @param bool $onlySameParentOrg | |
790 | * True if only Memberships with same parent org as the $memType wanted, false otherwise. | |
e46e9a0b EM |
791 | * |
792 | * @return array|bool | |
6a488035 | 793 | */ |
00be9182 | 794 | public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) { |
388d10d8 TC |
795 | //check for owner membership id, if it exists update that membership instead: CRM-15992 |
796 | if ($membershipId) { | |
797 | $ownerMemberId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', | |
798 | $membershipId, | |
799 | 'owner_membership_id', 'id' | |
800 | ); | |
801 | if ($ownerMemberId) { | |
802 | $membershipId = $ownerMemberId; | |
803 | $contactID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', | |
804 | $membershipId, | |
805 | 'contact_id', 'id' | |
806 | ); | |
807 | } | |
808 | } | |
809 | ||
6a488035 TO |
810 | $dao = new CRM_Member_DAO_Membership(); |
811 | if ($membershipId) { | |
812 | $dao->id = $membershipId; | |
813 | } | |
814 | $dao->contact_id = $contactID; | |
815 | $dao->membership_type_id = $memType; | |
816 | ||
817 | //fetch proper membership record. | |
818 | if ($isTest) { | |
819 | $dao->is_test = $isTest; | |
820 | } | |
821 | else { | |
822 | $dao->whereAdd('is_test IS NULL OR is_test = 0'); | |
823 | } | |
5624f515 | 824 | |
6a488035 | 825 | //avoid pending membership as current membership: CRM-3027 |
b6d493f3 | 826 | $statusIds = array(array_search('Pending', CRM_Member_PseudoConstant::membershipStatus())); |
b5a62499 | 827 | if (!$membershipId) { |
7ff60806 PN |
828 | // CRM-15475 |
829 | $statusIds[] = array_search( | |
4c16123d | 830 | 'Cancelled', |
7ff60806 | 831 | CRM_Member_PseudoConstant::membershipStatus( |
4c16123d EM |
832 | NULL, |
833 | " name = 'Cancelled' ", | |
834 | 'name', | |
835 | FALSE, | |
7ff60806 PN |
836 | TRUE |
837 | ) | |
838 | ); | |
b5a62499 | 839 | } |
e0556ebe | 840 | $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')'); |
5624f515 | 841 | |
6a488035 TO |
842 | // order by start date to find most recent membership first, CRM-4545 |
843 | $dao->orderBy('start_date DESC'); | |
844 | ||
845 | // CRM-8141 | |
846 | if ($onlySameParentOrg && $memType) { | |
847 | // require the same parent org as the $memType | |
848 | $params = array('id' => $memType); | |
5901ddf9 | 849 | $membershipType = array(); |
6a488035 | 850 | if (CRM_Member_BAO_MembershipType::retrieve($params, $membershipType)) { |
4c50ac3a MW |
851 | $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', array( |
852 | 'member_of_contact_id' => $membershipType['member_of_contact_id'], | |
c8eada29 MW |
853 | 'options' => array( |
854 | 'limit' => 0, | |
855 | ), | |
4c50ac3a MW |
856 | )); |
857 | $memberTypesSameParentOrgList = implode(',', array_keys(CRM_Utils_Array::value('values', $memberTypesSameParentOrg, array()))); | |
6a488035 TO |
858 | $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')'); |
859 | } | |
860 | } | |
861 | ||
862 | if ($dao->find(TRUE)) { | |
863 | $membership = array(); | |
864 | CRM_Core_DAO::storeValues($dao, $membership); | |
865 | $membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', | |
866 | $membership['status_id'], | |
867 | 'is_current_member', 'id' | |
868 | ); | |
0829c697 TC |
869 | $ownerMemberId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', |
870 | $membership['id'], | |
871 | 'owner_membership_id', 'id' | |
872 | ); | |
873 | if ($ownerMemberId) { | |
874 | $membership['id'] = $membership['membership_id'] = $ownerMemberId; | |
875 | $membership['membership_contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', | |
876 | $membership['id'], | |
877 | 'contact_id', 'id' | |
878 | ); | |
879 | } | |
6a488035 TO |
880 | return $membership; |
881 | } | |
882 | ||
883 | // CRM-8141 | |
884 | if ($onlySameParentOrg && $memType) { | |
885 | // see if there is a membership that has same parent as $memType but different parent than $membershipID | |
5682e889 | 886 | if ($dao->id && CRM_Core_Permission::check('edit memberships')) { |
887 | // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed. | |
e0556ebe | 888 | $dao->whereAdd(); |
5682e889 | 889 | } |
890 | else { | |
891 | unset($dao->id); | |
892 | } | |
6a488035 TO |
893 | |
894 | unset($dao->membership_type_id); | |
895 | if ($dao->find(TRUE)) { | |
896 | $membership = array(); | |
897 | CRM_Core_DAO::storeValues($dao, $membership); | |
898 | $membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', | |
899 | $membership['status_id'], | |
900 | 'is_current_member', 'id' | |
901 | ); | |
902 | return $membership; | |
903 | } | |
904 | } | |
905 | return FALSE; | |
906 | } | |
907 | ||
908 | /** | |
fe482240 | 909 | * Combine all the importable fields from the lower levels object. |
6a488035 | 910 | * |
b2363ea8 TO |
911 | * @param string $contactType |
912 | * Contact type. | |
913 | * @param bool $status | |
6a488035 | 914 | * |
a6c01b45 CW |
915 | * @return array |
916 | * array of importable Fields | |
6a488035 | 917 | */ |
00be9182 | 918 | public static function &importableFields($contactType = 'Individual', $status = TRUE) { |
6a488035 TO |
919 | if (!self::$_importableFields) { |
920 | if (!self::$_importableFields) { | |
921 | self::$_importableFields = array(); | |
922 | } | |
923 | ||
924 | if (!$status) { | |
925 | $fields = array('' => array('title' => '- ' . ts('do not import') . ' -')); | |
926 | } | |
927 | else { | |
928 | $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -')); | |
929 | } | |
930 | ||
931 | $tmpFields = CRM_Member_DAO_Membership::import(); | |
932 | $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL); | |
933 | ||
934 | // Using new Dedupe rule. | |
935 | $ruleParams = array( | |
936 | 'contact_type' => $contactType, | |
e0556ebe | 937 | 'used' => 'Unsupervised', |
6a488035 TO |
938 | ); |
939 | $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); | |
940 | ||
941 | $tmpContactField = array(); | |
942 | if (is_array($fieldsArray)) { | |
943 | foreach ($fieldsArray as $value) { | |
944 | $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', | |
945 | $value, | |
946 | 'id', | |
947 | 'column_name' | |
948 | ); | |
949 | $value = $customFieldId ? 'custom_' . $customFieldId : $value; | |
950 | $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields); | |
951 | if (!$status) { | |
952 | $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)'); | |
953 | } | |
954 | else { | |
955 | $title = $tmpContactField[trim($value)]['title']; | |
956 | } | |
957 | $tmpContactField[trim($value)]['title'] = $title; | |
958 | } | |
959 | } | |
960 | $tmpContactField['external_identifier'] = $contactFields['external_identifier']; | |
961 | $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)'); | |
962 | ||
963 | $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');; | |
964 | ||
965 | $fields = array_merge($fields, $tmpContactField); | |
966 | $fields = array_merge($fields, $tmpFields); | |
967 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership')); | |
968 | self::$_importableFields = $fields; | |
969 | } | |
970 | return self::$_importableFields; | |
971 | } | |
972 | ||
973 | /** | |
fe482240 | 974 | * Get all exportable fields. |
6a488035 | 975 | * |
06d062ce | 976 | * @return array return array of all exportable fields |
6a488035 | 977 | */ |
00be9182 | 978 | public static function &exportableFields() { |
6a488035 | 979 | $expFieldMembership = CRM_Member_DAO_Membership::export(); |
6a488035 TO |
980 | |
981 | $expFieldsMemType = CRM_Member_DAO_MembershipType::export(); | |
e0556ebe TO |
982 | $fields = array_merge($expFieldMembership, $expFieldsMemType); |
983 | $fields = array_merge($fields, $expFieldMembership); | |
6a488035 | 984 | $membershipStatus = array( |
e0556ebe | 985 | 'membership_status' => array( |
e300cf31 | 986 | 'title' => ts('Membership Status'), |
6a488035 TO |
987 | 'name' => 'membership_status', |
988 | 'type' => CRM_Utils_Type::T_STRING, | |
989 | 'where' => 'civicrm_membership_status.name', | |
21dfd5f5 | 990 | ), |
e0556ebe | 991 | ); |
6a488035 TO |
992 | //CRM-6161 fix for customdata export |
993 | $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField::getFieldsForImport('Membership')); | |
994 | return $fields; | |
995 | } | |
996 | ||
997 | /** | |
7b835f7c EM |
998 | * Get membership joins/renewals for a specified membership type. |
999 | * | |
1000 | * Specifically, retrieves a count of memberships whose "Membership | |
4e636a74 | 1001 | * Signup" or "Membership Renewal" activity falls in the given date range. |
8ef12e64 | 1002 | * Dates match the pattern "yyyy-mm-dd". |
6a488035 | 1003 | * |
b2363ea8 TO |
1004 | * @param int $membershipTypeId |
1005 | * Membership type id. | |
1006 | * @param int $startDate | |
1007 | * Date on which to start counting. | |
1008 | * @param int $endDate | |
1009 | * Date on which to end counting. | |
e46e9a0b EM |
1010 | * @param bool|int $isTest if true, membership is for a test site |
1011 | * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD | |
6a488035 | 1012 | * |
df8d3074 | 1013 | * @return int |
a6c01b45 | 1014 | * the number of members of type $membershipTypeId whose |
688d37c6 | 1015 | * start_date is between $startDate and $endDate |
6a488035 | 1016 | */ |
6a488035 | 1017 | public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) { |
8ef12e64 | 1018 | |
4e636a74 AH |
1019 | $testClause = 'membership.is_test = 1'; |
1020 | if (!$isTest) { | |
1021 | $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )'; | |
1022 | } | |
8ef12e64 | 1023 | |
4e636a74 AH |
1024 | if (!self::$_signupActType || !self::$_renewalActType) { |
1025 | self::_getActTypes(); | |
1026 | } | |
8ef12e64 | 1027 | |
4e636a74 AH |
1028 | if (!self::$_signupActType || !self::$_renewalActType) { |
1029 | return 0; | |
1030 | } | |
1031 | ||
1032 | $query = " | |
1033 | SELECT COUNT(DISTINCT membership.id) as member_count | |
1034 | FROM civicrm_membership membership | |
1035 | INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2)) | |
1036 | INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 ) | |
1037 | INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 ) | |
1038 | WHERE membership.membership_type_id = %3 | |
1039 | AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59' | |
1040 | AND {$testClause}"; | |
8ef12e64 | 1041 | |
6a488035 | 1042 | $query .= ($isOwner) ? ' AND owner_membership_id IS NULL' : ''; |
4e636a74 AH |
1043 | |
1044 | $params = array( | |
1045 | 1 => array(self::$_signupActType, 'Integer'), | |
1046 | 2 => array(self::$_renewalActType, 'Integer'), | |
8ef12e64 | 1047 | 3 => array($membershipTypeId, 'Integer'), |
6a488035 | 1048 | ); |
8ef12e64 | 1049 | |
6a488035 | 1050 | $memberCount = CRM_Core_DAO::singleValueQuery($query, $params); |
e0556ebe | 1051 | return (int) $memberCount; |
6a488035 TO |
1052 | } |
1053 | ||
1054 | /** | |
7b835f7c EM |
1055 | * Get a count of membership for a specified membership type, optionally for a specified date. |
1056 | * | |
1057 | * The date must have the form yyyy-mm-dd. | |
6a488035 TO |
1058 | * |
1059 | * If $date is omitted, this function counts as a member anyone whose | |
1060 | * membership status_id indicates they're a current member. | |
1061 | * If $date is given, this function counts as a member anyone who: | |
1062 | * -- Has a start_date before $date and end_date after $date, or | |
1063 | * -- Has a start_date before $date and is currently a member, as indicated | |
1064 | * by the the membership's status_id. | |
1065 | * The second condition takes care of records that have no end_date. These | |
1066 | * are assumed to be lifetime memberships. | |
1067 | * | |
b2363ea8 TO |
1068 | * @param int $membershipTypeId |
1069 | * Membership type id. | |
1070 | * @param string $date | |
1071 | * The date for which to retrieve the count. | |
e46e9a0b EM |
1072 | * @param bool|int $isTest if true, membership is for a test site |
1073 | * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD | |
6a488035 | 1074 | * |
72b3a70c CW |
1075 | * @return int |
1076 | * the number of members of type $membershipTypeId as of $date. | |
6a488035 TO |
1077 | */ |
1078 | public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) { | |
4e636a74 AH |
1079 | if (!CRM_Utils_Rule::date($date)) { |
1080 | CRM_Core_Error::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date))); | |
6a488035 TO |
1081 | } |
1082 | ||
e0556ebe TO |
1083 | $params = array( |
1084 | 1 => array($membershipTypeId, 'Integer'), | |
6a488035 TO |
1085 | 2 => array($isTest, 'Boolean'), |
1086 | ); | |
1087 | $query = "SELECT count(civicrm_membership.id ) as member_count | |
1088 | FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id ) | |
1089 | WHERE civicrm_membership.membership_type_id = %1 | |
1090 | AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1) | |
1091 | AND civicrm_membership.is_test = %2"; | |
1092 | if (!$date) { | |
1093 | $query .= " AND civicrm_membership_status.is_current_member = 1"; | |
1094 | } | |
1095 | else { | |
6a488035 TO |
1096 | $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1"; |
1097 | } | |
1098 | // LCD | |
1099 | $query .= ($isOwner) ? ' AND owner_membership_id IS NULL' : ''; | |
1100 | $memberCount = CRM_Core_DAO::singleValueQuery($query, $params); | |
e0556ebe | 1101 | return (int) $memberCount; |
6a488035 TO |
1102 | } |
1103 | ||
1104 | /** | |
fe482240 | 1105 | * Function check the status of the membership before adding membership for a contact. |
6a488035 | 1106 | * |
e46e9a0b | 1107 | * @return int |
6a488035 | 1108 | */ |
6a38708b | 1109 | public static function statusAvailabilty() { |
6a488035 TO |
1110 | $membership = new CRM_Member_DAO_MembershipStatus(); |
1111 | $membership->whereAdd('is_active=1'); | |
c905ba98 | 1112 | return $membership->count(); |
6a488035 TO |
1113 | } |
1114 | ||
cd125a40 | 1115 | /** |
7b835f7c | 1116 | * Function for updating a membership record's contribution_recur_id. |
cd125a40 | 1117 | * |
c866eb5f | 1118 | * @param CRM_Member_DAO_Membership $membership |
5901ddf9 | 1119 | * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution |
cd125a40 | 1120 | */ |
c866eb5f | 1121 | static public function updateRecurMembership(CRM_Member_DAO_Membership $membership, CRM_Contribute_BAO_Contribution $contribution) { |
cd125a40 FG |
1122 | |
1123 | if (empty($contribution->contribution_recur_id)) { | |
1124 | return; | |
1125 | } | |
1126 | ||
1127 | $params = array( | |
1128 | 1 => array($contribution->contribution_recur_id, 'Integer'), | |
1129 | 2 => array($membership->id, 'Integer'), | |
1130 | ); | |
1131 | ||
1132 | $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2"; | |
1133 | CRM_Core_DAO::executeQuery($sql, $params); | |
1134 | } | |
1135 | ||
6a488035 | 1136 | /** |
fe482240 | 1137 | * Method to fix membership status of stale membership. |
6a488035 TO |
1138 | * |
1139 | * This method first checks if the membership is stale. If it is, | |
1140 | * then status will be updated based on existing start and end | |
1141 | * dates and log will be added for the status change. | |
1142 | * | |
b2363ea8 TO |
1143 | * @param array $currentMembership |
1144 | * Reference to the array. | |
688d37c6 CW |
1145 | * containing all values of |
1146 | * the current membership | |
81716ddb EE |
1147 | * @param string $changeToday |
1148 | * In case today needs | |
688d37c6 | 1149 | * to be customised, null otherwise |
6a488035 | 1150 | */ |
00be9182 | 1151 | public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) { |
6a488035 TO |
1152 | $today = NULL; |
1153 | if ($changeToday) { | |
1154 | $today = CRM_Utils_Date::processDate($changeToday, NULL, FALSE, 'Y-m-d'); | |
1155 | } | |
1156 | ||
1157 | $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate( | |
1158 | CRM_Utils_Array::value('start_date', $currentMembership), | |
1159 | CRM_Utils_Array::value('end_date', $currentMembership), | |
1160 | CRM_Utils_Array::value('join_date', $currentMembership), | |
1161 | $today, | |
5f11bbcc EM |
1162 | TRUE, |
1163 | $currentMembership['membership_type_id'], | |
1164 | $currentMembership | |
6a488035 TO |
1165 | ); |
1166 | ||
1167 | if (empty($status) || | |
1168 | empty($status['id']) | |
1169 | ) { | |
1170 | CRM_Core_Error::fatal(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.')); | |
1171 | } | |
1172 | ||
1173 | $currentMembership['today_date'] = $today; | |
1174 | ||
1175 | if ($status['id'] !== $currentMembership['status_id']) { | |
c329a76a | 1176 | $oldStatus = $currentMembership['status_id']; |
6a488035 TO |
1177 | $memberDAO = new CRM_Member_DAO_Membership(); |
1178 | $memberDAO->id = $currentMembership['id']; | |
1179 | $memberDAO->find(TRUE); | |
1180 | ||
1181 | $memberDAO->status_id = $status['id']; | |
1182 | $memberDAO->join_date = CRM_Utils_Date::isoToMysql($memberDAO->join_date); | |
1183 | $memberDAO->start_date = CRM_Utils_Date::isoToMysql($memberDAO->start_date); | |
1184 | $memberDAO->end_date = CRM_Utils_Date::isoToMysql($memberDAO->end_date); | |
1185 | $memberDAO->save(); | |
1186 | CRM_Core_DAO::storeValues($memberDAO, $currentMembership); | |
1187 | $memberDAO->free(); | |
1188 | ||
1189 | $currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue( | |
1190 | 'CRM_Member_DAO_MembershipStatus', | |
1191 | $currentMembership['status_id'], | |
1192 | 'is_current_member' | |
1193 | ); | |
1194 | $format = '%Y%m%d'; | |
1195 | ||
1196 | $logParams = array( | |
1197 | 'membership_id' => $currentMembership['id'], | |
1198 | 'status_id' => $status['id'], | |
1199 | 'start_date' => CRM_Utils_Date::customFormat( | |
1200 | $currentMembership['start_date'], | |
1201 | $format | |
1202 | ), | |
1203 | 'end_date' => CRM_Utils_Date::customFormat( | |
1204 | $currentMembership['end_date'], | |
1205 | $format | |
1206 | ), | |
1207 | 'modified_date' => CRM_Utils_Date::customFormat( | |
1208 | $currentMembership['today_date'], | |
1209 | $format | |
1210 | ), | |
1211 | 'membership_type_id' => $currentMembership['membership_type_id'], | |
520c1a14 | 1212 | 'max_related' => CRM_Utils_Array::value('max_related', $currentMembership, 0), |
6a488035 TO |
1213 | ); |
1214 | ||
1215 | $session = CRM_Core_Session::singleton(); | |
1216 | // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id | |
1217 | if ($session->get('userID')) { | |
1218 | $logParams['modified_id'] = $session->get('userID'); | |
1219 | } | |
1220 | else { | |
1221 | $logParams['modified_id'] = $currentMembership['contact_id']; | |
1222 | } | |
c329a76a JP |
1223 | |
1224 | //Create activity for status change. | |
1225 | $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get'); | |
1226 | CRM_Activity_BAO_Activity::addActivity($memberDAO, | |
1227 | 'Change Membership Status', | |
1228 | NULL, | |
1229 | array( | |
1230 | 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}", | |
1231 | 'source_contact_id' => $logParams['modified_id'], | |
1232 | 'priority_id' => 'Normal', | |
1233 | ) | |
1234 | ); | |
1235 | ||
4ed92e91 | 1236 | CRM_Member_BAO_MembershipLog::add($logParams); |
6a488035 TO |
1237 | } |
1238 | } | |
1239 | ||
1240 | /** | |
fe482240 | 1241 | * Get the contribution page id from the membership record. |
6a488035 | 1242 | * |
688d37c6 | 1243 | * @param int $membershipID |
6a488035 | 1244 | * |
a6c01b45 | 1245 | * @return int |
688d37c6 | 1246 | * contribution page id |
6a488035 | 1247 | */ |
00be9182 | 1248 | public static function getContributionPageId($membershipID) { |
6a488035 TO |
1249 | $query = " |
1250 | SELECT c.contribution_page_id as pageID | |
1251 | FROM civicrm_membership_payment mp, civicrm_contribution c | |
1252 | WHERE mp.contribution_id = c.id | |
1253 | AND c.contribution_page_id IS NOT NULL | |
1254 | AND mp.membership_id = " . CRM_Utils_Type::escape($membershipID, 'Integer') | |
e0556ebe | 1255 | . " ORDER BY mp.id DESC"; |
6a488035 TO |
1256 | |
1257 | return CRM_Core_DAO::singleValueQuery($query, | |
1258 | CRM_Core_DAO::$_nullArray | |
1259 | ); | |
1260 | } | |
1261 | ||
6a488035 | 1262 | /** |
fe482240 | 1263 | * Updated related memberships. |
6a488035 | 1264 | * |
b2363ea8 TO |
1265 | * @param int $ownerMembershipId |
1266 | * Owner Membership Id. | |
1267 | * @param array $params | |
1268 | * Formatted array of key => value. | |
6a488035 | 1269 | */ |
00be9182 | 1270 | public static function updateRelatedMemberships($ownerMembershipId, $params) { |
6a488035 TO |
1271 | $membership = new CRM_Member_DAO_Membership(); |
1272 | $membership->owner_membership_id = $ownerMembershipId; | |
1273 | $membership->find(); | |
1274 | ||
1275 | while ($membership->fetch()) { | |
1276 | $relatedMembership = new CRM_Member_DAO_Membership(); | |
1277 | $relatedMembership->id = $membership->id; | |
1278 | $relatedMembership->copyValues($params); | |
1279 | $relatedMembership->save(); | |
1280 | $relatedMembership->free(); | |
1281 | } | |
1282 | ||
1283 | $membership->free(); | |
1284 | } | |
1285 | ||
1286 | /** | |
fe482240 | 1287 | * Get list of membership fields for profile. |
7b835f7c | 1288 | * |
6a488035 TO |
1289 | * For now we only allow custom membership fields to be in |
1290 | * profile | |
1291 | * | |
e46e9a0b | 1292 | * @param null $mode |
688d37c6 | 1293 | * FIXME: This param is ignored |
e46e9a0b | 1294 | * |
a6c01b45 CW |
1295 | * @return array |
1296 | * the list of membership fields | |
6a488035 | 1297 | */ |
00be9182 | 1298 | public static function getMembershipFields($mode = NULL) { |
6a488035 TO |
1299 | $fields = CRM_Member_DAO_Membership::export(); |
1300 | ||
6a488035 TO |
1301 | unset($fields['membership_contact_id']); |
1302 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership')); | |
1303 | ||
1304 | $membershipType = CRM_Member_DAO_MembershipType::export(); | |
1305 | ||
1306 | $membershipStatus = CRM_Member_DAO_MembershipStatus::export(); | |
1307 | ||
1308 | $fields = array_merge($fields, $membershipType, $membershipStatus); | |
1309 | ||
1310 | return $fields; | |
1311 | } | |
1312 | ||
1313 | /** | |
fe482240 | 1314 | * Get the sort name of a contact for a particular membership. |
6a488035 | 1315 | * |
b2363ea8 TO |
1316 | * @param int $id |
1317 | * Id of the membership. | |
6a488035 | 1318 | * |
72b3a70c CW |
1319 | * @return null|string |
1320 | * sort name of the contact if found | |
6a488035 | 1321 | */ |
00be9182 | 1322 | public static function sortName($id) { |
6a488035 TO |
1323 | $id = CRM_Utils_Type::escape($id, 'Integer'); |
1324 | ||
1325 | $query = " | |
1326 | SELECT civicrm_contact.sort_name | |
1327 | FROM civicrm_membership, civicrm_contact | |
1328 | WHERE civicrm_membership.contact_id = civicrm_contact.id | |
1329 | AND civicrm_membership.id = {$id} | |
1330 | "; | |
f7969dcf | 1331 | return CRM_Core_DAO::singleValueQuery($query); |
6a488035 TO |
1332 | } |
1333 | ||
1334 | /** | |
7b835f7c | 1335 | * Create memberships for related contacts, taking into account the maximum related memberships. |
6a488035 | 1336 | * |
b2363ea8 TO |
1337 | * @param array $params |
1338 | * Array of key - value pairs. | |
1339 | * @param CRM_Core_DAO $dao | |
1340 | * Membership object. | |
6a488035 | 1341 | * |
06d062ce EM |
1342 | * @param bool $reset |
1343 | * | |
1344 | * @return array|null | |
1345 | * Membership details, if created. | |
1346 | * | |
1347 | * @throws \CRM_Core_Exception | |
6a488035 | 1348 | */ |
00be9182 | 1349 | public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) { |
49903ed2 | 1350 | // CRM-4213 check for loops, using static variable to record contacts already processed. |
6a488035 | 1351 | static $relatedContactIds = array(); |
6d8a45ed | 1352 | if ($reset) { |
49903ed2 DJ |
1353 | // We need a way to reset this static variable from the test suite. |
1354 | // @todo consider replacing with Civi::$statics but note reset now used elsewhere: CRM-17723. | |
6d8a45ed | 1355 | $relatedContactIds = array(); |
608e6658 | 1356 | return FALSE; |
6d8a45ed | 1357 | } |
6a488035 TO |
1358 | |
1359 | $membership = new CRM_Member_DAO_Membership(); | |
1360 | $membership->id = $dao->id; | |
1361 | ||
1362 | // required since create method doesn't return all the | |
1363 | // parameters in the returned membership object | |
1364 | if (!$membership->find(TRUE)) { | |
1365 | return; | |
1366 | } | |
1367 | $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus()); | |
1368 | // FIXME : While updating/ renewing the | |
1369 | // membership, if the relationship is PAST then | |
1370 | // the membership of the related contact must be | |
1371 | // expired. | |
1372 | // For that, getting Membership Status for which | |
1373 | // is_current_member is 0. It works for the | |
1374 | // generated data as there is only one membership | |
1375 | // status having is_current_member = 0. | |
1376 | // But this wont work exactly if there will be | |
1377 | // more than one status having is_current_member = 0. | |
1378 | $membershipStatus = new CRM_Member_DAO_MembershipStatus(); | |
1379 | $membershipStatus->is_current_member = 0; | |
1380 | if ($membershipStatus->find(TRUE)) { | |
1381 | $expiredStatusId = $membershipStatus->id; | |
e0556ebe TO |
1382 | } |
1383 | else { | |
6a488035 TO |
1384 | $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant::membershipStatus()); |
1385 | } | |
1386 | ||
1387 | $allRelatedContacts = array(); | |
1388 | $relatedContacts = array(); | |
1389 | if (!is_a($membership, 'CRM_Core_Error')) { | |
5c3a7abf | 1390 | $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->membership_type_id, |
6a488035 TO |
1391 | $membership->contact_id, |
1392 | CRM_Utils_Array::value('action', $params) | |
1393 | ); | |
1394 | } | |
1395 | ||
49903ed2 DJ |
1396 | // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed. |
1397 | // Remove repeated related contacts, which already inherited membership of this type. | |
1398 | $relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE; | |
6a488035 | 1399 | foreach ($allRelatedContacts as $cid => $status) { |
49903ed2 DJ |
1400 | if (empty($relatedContactIds[$cid]) || empty($relatedContactIds[$cid][$membership->membership_type_id])) { |
1401 | $relatedContactIds[$cid][$membership->membership_type_id] = TRUE; | |
6a488035 TO |
1402 | |
1403 | //don't create membership again for owner contact. | |
1404 | $nestedRelationship = FALSE; | |
1405 | if ($membership->owner_membership_id) { | |
1406 | $nestedRelMembership = new CRM_Member_DAO_Membership(); | |
1407 | $nestedRelMembership->id = $membership->owner_membership_id; | |
1408 | $nestedRelMembership->contact_id = $cid; | |
1409 | $nestedRelationship = $nestedRelMembership->find(TRUE); | |
1410 | $nestedRelMembership->free(); | |
1411 | } | |
1412 | if (!$nestedRelationship) { | |
1413 | $relatedContacts[$cid] = $status; | |
1414 | } | |
1415 | } | |
1416 | } | |
1417 | ||
1418 | //lets cleanup related membership if any. | |
1419 | if (empty($relatedContacts)) { | |
3506b6cd | 1420 | self::deleteRelatedMemberships($membership->id); |
6a488035 TO |
1421 | } |
1422 | else { | |
1423 | // Edit the params array | |
1424 | unset($params['id']); | |
1425 | // Reminder should be sent only to the direct membership | |
1426 | unset($params['reminder_date']); | |
1427 | // unset the custom value ids | |
1428 | if (is_array(CRM_Utils_Array::value('custom', $params))) { | |
1429 | foreach ($params['custom'] as $k => $v) { | |
1430 | unset($params['custom'][$k]['id']); | |
1431 | } | |
1432 | } | |
1433 | if (!isset($params['membership_type_id'])) { | |
1434 | $params['membership_type_id'] = $membership->membership_type_id; | |
1435 | } | |
1436 | ||
1437 | // max_related should be set in the parent membership | |
1438 | unset($params['max_related']); | |
1439 | // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none | |
e48744e2 | 1440 | $numRelatedAvailable = ($membership->max_related == NULL ? PHP_INT_MAX : $membership->max_related); |
7b835f7c EM |
1441 | // will be used to queue potential memberships to be created. |
1442 | $queue = array(); | |
6a488035 TO |
1443 | |
1444 | foreach ($relatedContacts as $contactId => $relationshipStatus) { | |
1445 | //use existing membership record. | |
1446 | $relMembership = new CRM_Member_DAO_Membership(); | |
1447 | $relMembership->contact_id = $contactId; | |
1448 | $relMembership->owner_membership_id = $membership->id; | |
1449 | $relMemIds = array(); | |
1450 | if ($relMembership->find(TRUE)) { | |
1451 | $params['id'] = $relMemIds['membership'] = $relMembership->id; | |
1452 | } | |
1453 | $params['contact_id'] = $contactId; | |
1454 | $params['owner_membership_id'] = $membership->id; | |
1455 | ||
1456 | // set status_id as it might have been changed for | |
1457 | // past relationship | |
1458 | $params['status_id'] = $membership->status_id; | |
1459 | ||
1460 | if ($deceasedStatusId && | |
1461 | CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased') | |
1462 | ) { | |
1463 | $params['status_id'] = $deceasedStatusId; | |
1464 | } | |
1465 | elseif ((CRM_Utils_Array::value('action', $params) & CRM_Core_Action::UPDATE) && | |
1466 | ($relationshipStatus == CRM_Contact_BAO_Relationship::PAST) | |
1467 | ) { | |
e0556ebe TO |
1468 | $params['status_id'] = $expiredStatusId; |
1469 | } | |
6a488035 TO |
1470 | |
1471 | //don't calculate status again in create( ); | |
1472 | $params['skipStatusCal'] = TRUE; | |
1473 | ||
1474 | //do create activity if we changed status. | |
1475 | if ($params['status_id'] != $relMembership->status_id) { | |
1476 | $params['createActivity'] = TRUE; | |
1477 | } | |
1478 | ||
79192d1d BS |
1479 | //CRM-20707 - include start/end date |
1480 | $params['start_date'] = $membership->start_date; | |
1481 | $params['end_date'] = $membership->end_date; | |
1482 | ||
6a488035 TO |
1483 | // we should not created contribution record for related contacts, CRM-3371 |
1484 | unset($params['contribution_status_id']); | |
1485 | ||
63e1c32b WA |
1486 | //CRM-16857: Do not create multiple line-items for inherited membership through priceset. |
1487 | unset($params['lineItems']); | |
1488 | unset($params['line_item']); | |
1489 | ||
e53bcaa3 DJ |
1490 | // CRM-20966: Do not create membership_payment record for inherited membership. |
1491 | unset($params['relate_contribution_id']); | |
1492 | ||
6a488035 TO |
1493 | if (($params['status_id'] == $deceasedStatusId) || ($params['status_id'] == $expiredStatusId)) { |
1494 | // related membership is not active so does not count towards maximum | |
1495 | CRM_Member_BAO_Membership::create($params, $relMemIds); | |
8efea814 EM |
1496 | } |
1497 | else { | |
6a488035 TO |
1498 | // related membership already exists, so this is just an update |
1499 | if (isset($params['id'])) { | |
e48744e2 | 1500 | if ($numRelatedAvailable > 0) { |
e0556ebe | 1501 | CRM_Member_BAO_Membership::create($params, $relMemIds); |
e48744e2 | 1502 | $numRelatedAvailable--; |
e0556ebe | 1503 | } |
608e6658 | 1504 | else { |
1505 | // we have run out of inherited memberships, so delete extras | |
f5e53870 | 1506 | self::deleteMembership($params['id']); |
6a488035 | 1507 | } |
e0556ebe TO |
1508 | // we need to first check if there will remain inherited memberships, so queue it up |
1509 | } | |
1510 | else { | |
6a488035 TO |
1511 | $queue[] = $params; |
1512 | } | |
1513 | } | |
1514 | } | |
1515 | // now go over the queue and create any available related memberships | |
e48744e2 SL |
1516 | foreach ($queue as $params) { |
1517 | if ($numRelatedAvailable <= 0) { | |
1518 | break; | |
1519 | } | |
1520 | CRM_Member_BAO_Membership::create($params, $relMemIds); | |
1521 | $numRelatedAvailable--; | |
6a488035 TO |
1522 | } |
1523 | } | |
1524 | } | |
1525 | ||
1526 | /** | |
fe482240 | 1527 | * Delete the record that are associated with this Membership Payment. |
6a488035 | 1528 | * |
b2363ea8 | 1529 | * @param int $membershipId |
6a488035 | 1530 | * |
608e6658 | 1531 | * @return object |
1532 | * $membershipPayment deleted membership payment object | |
6a488035 | 1533 | */ |
086fea8e | 1534 | public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) { |
6a488035 | 1535 | |
608e6658 | 1536 | $membershipPayment = new CRM_Member_DAO_MembershipPayment(); |
1537 | $membershipPayment->membership_id = $membershipId; | |
1538 | $membershipPayment->find(); | |
6a488035 | 1539 | |
608e6658 | 1540 | while ($membershipPayment->fetch()) { |
ed4cc29d JT |
1541 | if (!$preserveContrib) { |
1542 | CRM_Contribute_BAO_Contribution::deleteContribution($membershipPayment->contribution_id); | |
1543 | } | |
608e6658 | 1544 | CRM_Utils_Hook::pre('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment); |
061a8a1e | 1545 | $membershipPayment->delete(); |
608e6658 | 1546 | CRM_Utils_Hook::post('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment); |
6a488035 | 1547 | } |
608e6658 | 1548 | return $membershipPayment; |
6a488035 TO |
1549 | } |
1550 | ||
bb3a214a | 1551 | /** |
ab30e033 EM |
1552 | * Build an array of available membership types. |
1553 | * | |
c490a46a | 1554 | * @param CRM_Core_Form $form |
1a00ea3c | 1555 | * @param array $membershipTypeID |
ab30e033 EM |
1556 | * @param bool $activeOnly |
1557 | * Do we only want active ones? | |
1558 | * (probably this should default to TRUE but as a newly added parameter we are leaving default b | |
1559 | * behaviour unchanged). | |
bb3a214a EM |
1560 | * |
1561 | * @return array | |
1562 | */ | |
1a00ea3c | 1563 | public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) { |
e0556ebe | 1564 | $whereClause = " WHERE domain_id = " . CRM_Core_Config::domainID(); |
1a00ea3c | 1565 | $membershipTypeIDS = (array) $membershipTypeID; |
6a488035 | 1566 | |
ab30e033 EM |
1567 | if ($activeOnly) { |
1568 | $whereClause .= " AND is_active = 1 "; | |
1569 | } | |
1a00ea3c EM |
1570 | if (!empty($membershipTypeIDS)) { |
1571 | $allIDs = implode(',', $membershipTypeIDS); | |
6a488035 TO |
1572 | $whereClause .= " AND id IN ( $allIDs )"; |
1573 | } | |
573fd305 | 1574 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD); |
8233fa90 E |
1575 | |
1576 | if ($financialTypes) { | |
40c655aa E |
1577 | $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; |
1578 | } | |
8233fa90 E |
1579 | else { |
1580 | $whereClause .= " AND financial_type_id IN (0)"; | |
1581 | } | |
6a488035 TO |
1582 | |
1583 | $query = " | |
1584 | SELECT * | |
1585 | FROM civicrm_membership_type | |
1586 | $whereClause; | |
1587 | "; | |
1588 | $dao = CRM_Core_DAO::executeQuery($query); | |
1589 | ||
1590 | $membershipTypeValues = array(); | |
1591 | $membershipTypeFields = array( | |
e0556ebe TO |
1592 | 'id', |
1593 | 'minimum_fee', | |
1594 | 'name', | |
1595 | 'is_active', | |
1596 | 'description', | |
1597 | 'financial_type_id', | |
1598 | 'auto_renew', | |
1599 | 'member_of_contact_id', | |
1600 | 'relationship_type_id', | |
1601 | 'relationship_direction', | |
1602 | 'max_related', | |
ab30e033 EM |
1603 | 'duration_unit', |
1604 | 'duration_interval', | |
6a488035 TO |
1605 | ); |
1606 | ||
1607 | while ($dao->fetch()) { | |
1608 | $membershipTypeValues[$dao->id] = array(); | |
1609 | foreach ($membershipTypeFields as $mtField) { | |
1610 | $membershipTypeValues[$dao->id][$mtField] = $dao->$mtField; | |
1611 | } | |
1612 | } | |
1613 | $dao->free(); | |
1614 | ||
1615 | CRM_Utils_Hook::membershipTypeValues($form, $membershipTypeValues); | |
1616 | ||
1617 | if (is_numeric($membershipTypeID) && | |
1618 | $membershipTypeID > 0 | |
1619 | ) { | |
1620 | return $membershipTypeValues[$membershipTypeID]; | |
1621 | } | |
1622 | else { | |
1623 | return $membershipTypeValues; | |
1624 | } | |
1625 | } | |
1626 | ||
1627 | /** | |
fe482240 | 1628 | * Get membership record count for a Contact. |
6a488035 | 1629 | * |
c490a46a | 1630 | * @param int $contactID |
b2363ea8 | 1631 | * @param bool $activeOnly |
6a488035 | 1632 | * |
c490a46a | 1633 | * @return null|string |
6a488035 | 1634 | */ |
00be9182 | 1635 | public static function getContactMembershipCount($contactID, $activeOnly = FALSE) { |
1484ea61 E |
1636 | CRM_Financial_BAO_FinancialType::getAvailableMembershipTypes($membershipTypes); |
1637 | $addWhere = " AND membership_type_id IN (0)"; | |
1638 | if (!empty($membershipTypes)) { | |
40c655aa | 1639 | $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")"; |
1484ea61 | 1640 | } |
6a488035 | 1641 | $select = "SELECT count(*) FROM civicrm_membership "; |
e0556ebe | 1642 | $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 "; |
6a488035 TO |
1643 | |
1644 | // CRM-6627, all status below 3 (active, pending, grace) are considered active | |
1645 | if ($activeOnly) { | |
1646 | $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id "; | |
e0556ebe | 1647 | $where .= " and civicrm_membership_status.is_current_member = 1"; |
6a488035 TO |
1648 | } |
1649 | ||
1484ea61 | 1650 | $query = $select . $where . $addWhere; |
6a488035 TO |
1651 | return CRM_Core_DAO::singleValueQuery($query); |
1652 | } | |
1653 | ||
1654 | /** | |
7b835f7c | 1655 | * Check whether payment processor supports cancellation of membership subscription. |
6a488035 | 1656 | * |
b2363ea8 TO |
1657 | * @param int $mid |
1658 | * Membership id. | |
6a488035 | 1659 | * |
e46e9a0b EM |
1660 | * @param bool $isNotCancelled |
1661 | * | |
608e6658 | 1662 | * @return bool |
6a488035 | 1663 | */ |
00be9182 | 1664 | public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) { |
6a488035 TO |
1665 | $cacheKeyString = "$mid"; |
1666 | $cacheKeyString .= $isNotCancelled ? '_1' : '_0'; | |
1667 | ||
1668 | static $supportsCancel = array(); | |
1669 | ||
1670 | if (!array_key_exists($cacheKeyString, $supportsCancel)) { | |
1671 | $supportsCancel[$cacheKeyString] = FALSE; | |
1672 | $isCancelled = FALSE; | |
1673 | ||
1674 | if ($isNotCancelled) { | |
1675 | $isCancelled = self::isSubscriptionCancelled($mid); | |
1676 | } | |
1677 | ||
1678 | $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($mid, 'membership', 'obj'); | |
1679 | if (!empty($paymentObject)) { | |
1524a007 | 1680 | $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled; |
6a488035 TO |
1681 | } |
1682 | } | |
1683 | return $supportsCancel[$cacheKeyString]; | |
1684 | } | |
1685 | ||
1686 | /** | |
fe482240 | 1687 | * Check whether subscription is already cancelled. |
6a488035 | 1688 | * |
b2363ea8 TO |
1689 | * @param int $mid |
1690 | * Membership id. | |
6a488035 | 1691 | * |
a6c01b45 CW |
1692 | * @return string |
1693 | * contribution status | |
6a488035 | 1694 | */ |
00be9182 | 1695 | public static function isSubscriptionCancelled($mid) { |
6a488035 TO |
1696 | $sql = " |
1697 | SELECT cr.contribution_status_id | |
1698 | FROM civicrm_contribution_recur cr | |
1699 | LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id ) | |
1700 | WHERE mem.id = %1 LIMIT 1"; | |
e0556ebe | 1701 | $params = array(1 => array($mid, 'Integer')); |
6a488035 | 1702 | $statusId = CRM_Core_DAO::singleValueQuery($sql, $params); |
e0556ebe | 1703 | $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name'); |
6a488035 TO |
1704 | if ($status == 'Cancelled') { |
1705 | return TRUE; | |
1706 | } | |
1707 | return FALSE; | |
1708 | } | |
1709 | ||
1710 | /** | |
7b835f7c EM |
1711 | * Get membership joins for a specified membership type. |
1712 | * | |
1713 | * Specifically, retrieves a count of still current memberships whose | |
4e636a74 | 1714 | * join_date and start_date are within a specified date range. Dates match |
8ef12e64 | 1715 | * the pattern "yyyy-mm-dd". |
6a488035 | 1716 | * |
b2363ea8 TO |
1717 | * @param int $membershipTypeId |
1718 | * Membership type id. | |
1719 | * @param int $startDate | |
1720 | * Date on which to start counting. | |
1721 | * @param int $endDate | |
1722 | * Date on which to end counting. | |
e46e9a0b | 1723 | * @param bool|int $isTest if true, membership is for a test site |
6a488035 | 1724 | * |
72b3a70c CW |
1725 | * @return int |
1726 | * the number of members of type $membershipTypeId | |
1727 | * whose join_date is between $startDate and $endDate and | |
1728 | * whose start_date is between $startDate and $endDate | |
6a488035 | 1729 | */ |
00be9182 | 1730 | public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) { |
6a488035 TO |
1731 | $testClause = 'membership.is_test = 1'; |
1732 | if (!$isTest) { | |
1733 | $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )'; | |
1734 | } | |
4e636a74 AH |
1735 | if (!self::$_signupActType) { |
1736 | self::_getActTypes(); | |
1737 | } | |
8ef12e64 | 1738 | |
4e636a74 AH |
1739 | if (!self::$_signupActType) { |
1740 | return 0; | |
1741 | } | |
6a488035 TO |
1742 | |
1743 | $query = " | |
8ef12e64 | 1744 | SELECT COUNT(DISTINCT membership.id) as member_count |
6a488035 | 1745 | FROM civicrm_membership membership |
8ef12e64 | 1746 | INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1) |
6a488035 | 1747 | INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 ) |
4e636a74 AH |
1748 | INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 ) |
1749 | WHERE membership.membership_type_id = %2 | |
1750 | AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59' | |
6a488035 TO |
1751 | AND {$testClause}"; |
1752 | ||
4e636a74 AH |
1753 | $params = array( |
1754 | 1 => array(self::$_signupActType, 'Integer'), | |
1755 | 2 => array($membershipTypeId, 'Integer'), | |
1756 | ); | |
1757 | ||
6a488035 TO |
1758 | $memberCount = CRM_Core_DAO::singleValueQuery($query, $params); |
1759 | ||
e0556ebe | 1760 | return (int) $memberCount; |
6a488035 TO |
1761 | } |
1762 | ||
1763 | /** | |
7b835f7c EM |
1764 | * Get membership renewals for a specified membership type. |
1765 | * | |
1766 | * Specifically, retrieves a count of still current memberships | |
8ef12e64 | 1767 | * whose join_date is before and start_date is within a specified date |
4e636a74 | 1768 | * range. Dates match the pattern "yyyy-mm-dd". |
6a488035 | 1769 | * |
b2363ea8 TO |
1770 | * @param int $membershipTypeId |
1771 | * Membership type id. | |
1772 | * @param int $startDate | |
1773 | * Date on which to start counting. | |
1774 | * @param int $endDate | |
1775 | * Date on which to end counting. | |
e46e9a0b | 1776 | * @param bool|int $isTest if true, membership is for a test site |
6a488035 | 1777 | * |
df8d3074 | 1778 | * @return int |
a6c01b45 | 1779 | * returns the number of members of type $membershipTypeId |
688d37c6 CW |
1780 | * whose join_date is before $startDate and |
1781 | * whose start_date is between $startDate and $endDate | |
6a488035 | 1782 | */ |
00be9182 | 1783 | public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) { |
6a488035 TO |
1784 | $testClause = 'membership.is_test = 1'; |
1785 | if (!$isTest) { | |
1786 | $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )'; | |
1787 | } | |
4e636a74 AH |
1788 | if (!self::$_renewalActType) { |
1789 | self::_getActTypes(); | |
1790 | } | |
8ef12e64 | 1791 | |
4e636a74 AH |
1792 | if (!self::$_renewalActType) { |
1793 | return 0; | |
1794 | } | |
6a488035 TO |
1795 | |
1796 | $query = " | |
8ef12e64 | 1797 | SELECT COUNT(DISTINCT membership.id) as member_count |
6a488035 | 1798 | FROM civicrm_membership membership |
4e636a74 | 1799 | INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1) |
6a488035 TO |
1800 | INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 ) |
1801 | INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 ) | |
4e636a74 | 1802 | WHERE membership.membership_type_id = %2 |
8ef12e64 | 1803 | AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59' |
6a488035 TO |
1804 | AND {$testClause}"; |
1805 | ||
4e636a74 AH |
1806 | $params = array( |
1807 | 1 => array(self::$_renewalActType, 'Integer'), | |
1808 | 2 => array($membershipTypeId, 'Integer'), | |
1809 | ); | |
6a488035 TO |
1810 | $memberCount = CRM_Core_DAO::singleValueQuery($query, $params); |
1811 | ||
e0556ebe | 1812 | return (int) $memberCount; |
6a488035 TO |
1813 | } |
1814 | ||
0547ad7d EM |
1815 | /** |
1816 | * Create linkages between membership & contribution - note this is the wrong place for this code but this is a | |
1817 | * refactoring step. This should be BAO functionality | |
1818 | * @param $membership | |
1819 | * @param $membershipContribution | |
1820 | */ | |
1821 | public static function linkMembershipPayment($membership, $membershipContribution) { | |
e0556ebe | 1822 | CRM_Member_BAO_MembershipPayment::create(array( |
353ffa53 | 1823 | 'membership_id' => $membership->id, |
67dbb78c | 1824 | 'membership_type_id' => $membership->membership_type_id, |
353ffa53 TO |
1825 | 'contribution_id' => $membershipContribution->id, |
1826 | )); | |
0547ad7d EM |
1827 | } |
1828 | ||
c98997b9 | 1829 | /** |
b2363ea8 | 1830 | * @param int $contactID |
100fef9d | 1831 | * @param int $membershipTypeID |
c98997b9 | 1832 | * @param bool $is_test |
81716ddb | 1833 | * @param string $changeToday |
b2363ea8 | 1834 | * @param int $modifiedID |
c98997b9 EM |
1835 | * @param $customFieldsFormatted |
1836 | * @param $numRenewTerms | |
100fef9d | 1837 | * @param int $membershipID |
c98997b9 | 1838 | * @param $pending |
b2363ea8 | 1839 | * @param int $contributionRecurID |
c98997b9 | 1840 | * @param $membershipSource |
c98997b9 | 1841 | * @param $isPayLater |
b2363ea8 | 1842 | * @param int $campaignId |
620ce374 | 1843 | * @param array $formDates |
13a16f43 | 1844 | * @param null|CRM_Contribute_BAO_Contribution $contribution |
8e8d287f | 1845 | * @param array $lineItems |
c98997b9 | 1846 | * |
c98997b9 | 1847 | * @return array |
13a16f43 | 1848 | * @throws \CRM_Core_Exception |
c98997b9 | 1849 | */ |
13a16f43 | 1850 | public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) { |
c98997b9 | 1851 | $renewalMode = $updateStatusId = FALSE; |
61767a1d EM |
1852 | $allStatus = CRM_Member_PseudoConstant::membershipStatus(); |
1853 | $format = '%Y%m%d'; | |
1854 | $statusFormat = '%Y-%m-%d'; | |
1855 | $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID); | |
c98997b9 | 1856 | $dates = array(); |
356bfcaf | 1857 | $ids = array(); |
d81c67a2 | 1858 | // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType |
c98997b9 EM |
1859 | // is the same as the parent org of an existing membership of the contact |
1860 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID, | |
1861 | $is_test, $membershipID, TRUE | |
1862 | ); | |
1863 | if ($currentMembership) { | |
c98997b9 EM |
1864 | $renewalMode = TRUE; |
1865 | ||
1866 | // Do NOT do anything. | |
1867 | //1. membership with status : PENDING/CANCELLED (CRM-2395) | |
1868 | //2. Paylater/IPN renew. CRM-4556. | |
e0556ebe | 1869 | if ($pending || in_array($currentMembership['status_id'], array( |
c5c263ca AH |
1870 | array_search('Pending', $allStatus), |
1871 | // CRM-15475 | |
1872 | array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), | |
1873 | ))) { | |
c98997b9 | 1874 | |
356bfcaf | 1875 | $memParams = array( |
1876 | 'id' => $currentMembership['id'], | |
1877 | 'contribution' => $contribution, | |
1878 | 'status_id' => $currentMembership['status_id'], | |
1879 | 'start_date' => $currentMembership['start_date'], | |
1880 | 'end_date' => $currentMembership['end_date'], | |
13a16f43 | 1881 | 'line_item' => $lineItems, |
356bfcaf | 1882 | 'join_date' => $currentMembership['join_date'], |
c98997b9 | 1883 | 'membership_type_id' => $membershipTypeID, |
ef0abb4c | 1884 | 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL, |
98f0683a | 1885 | 'membership_activity_status' => ($pending || $isPayLater) ? 'Scheduled' : 'Completed', |
c98997b9 | 1886 | ); |
14065266 | 1887 | if ($contributionRecurID) { |
356bfcaf | 1888 | $memParams['contribution_recur_id'] = $contributionRecurID; |
c98997b9 | 1889 | } |
d2460a89 MD |
1890 | |
1891 | $membership = self::create($memParams, $ids, FALSE); | |
f82cf0ed | 1892 | return array($membership, $renewalMode, $dates); |
c98997b9 EM |
1893 | } |
1894 | ||
1895 | // Check and fix the membership if it is STALE | |
1896 | self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); | |
1897 | ||
1898 | // Now Renew the membership | |
1899 | if (!$currentMembership['is_current_member']) { | |
1900 | // membership is not CURRENT | |
1901 | ||
1902 | // CRM-7297 Membership Upsell - calculate dates based on new membership type | |
1903 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'], | |
1904 | $changeToday, | |
1905 | $membershipTypeID, | |
1906 | $numRenewTerms | |
1907 | ); | |
1908 | ||
1909 | $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); | |
620ce374 | 1910 | foreach (array('start_date', 'end_date') as $dateType) { |
1911 | $currentMembership[$dateType] = CRM_Utils_Array::value($dateType, $formDates); | |
1912 | if (empty($currentMembership[$dateType])) { | |
1913 | $currentMembership[$dateType] = CRM_Utils_Array::value($dateType, $dates); | |
1914 | } | |
1915 | } | |
c98997b9 EM |
1916 | $currentMembership['is_test'] = $is_test; |
1917 | ||
1918 | if (!empty($membershipSource)) { | |
1919 | $currentMembership['source'] = $membershipSource; | |
1920 | } | |
1921 | else { | |
1922 | $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', | |
1923 | $currentMembership['id'], | |
1924 | 'source' | |
1925 | ); | |
1926 | } | |
1927 | ||
1928 | if (!empty($currentMembership['id'])) { | |
1929 | $ids['membership'] = $currentMembership['id']; | |
1930 | } | |
1931 | $memParams = $currentMembership; | |
1932 | $memParams['membership_type_id'] = $membershipTypeID; | |
1933 | ||
1934 | //set the log start date. | |
1935 | $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); | |
1936 | } | |
1937 | else { | |
1938 | ||
1939 | // CURRENT Membership | |
1940 | $membership = new CRM_Member_DAO_Membership(); | |
1941 | $membership->id = $currentMembership['id']; | |
1942 | $membership->find(TRUE); | |
1943 | // CRM-7297 Membership Upsell - calculate dates based on new membership type | |
1944 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, | |
1945 | $changeToday, | |
1946 | $membershipTypeID, | |
1947 | $numRenewTerms | |
1948 | ); | |
1949 | ||
1950 | // Insert renewed dates for CURRENT membership | |
1951 | $memParams = array(); | |
1952 | $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date); | |
04b40eab | 1953 | $memParams['start_date'] = CRM_Utils_Array::value('start_date', $formDates, CRM_Utils_Date::isoToMysql($membership->start_date)); |
620ce374 | 1954 | $memParams['end_date'] = CRM_Utils_Array::value('end_date', $formDates); |
1955 | if (empty($memParams['end_date'])) { | |
1956 | $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates); | |
1957 | } | |
c98997b9 EM |
1958 | $memParams['membership_type_id'] = $membershipTypeID; |
1959 | ||
1960 | //set the log start date. | |
1961 | $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); | |
e7d41583 BS |
1962 | |
1963 | //CRM-18067 | |
1964 | if (!empty($membershipSource)) { | |
1965 | $memParams['source'] = $membershipSource; | |
1966 | } | |
1967 | elseif (empty($membership->source)) { | |
1968 | $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', | |
1969 | $currentMembership['id'], | |
1970 | 'source' | |
1971 | ); | |
c98997b9 EM |
1972 | } |
1973 | ||
1974 | if (!empty($currentMembership['id'])) { | |
1975 | $ids['membership'] = $currentMembership['id']; | |
1976 | } | |
c329a76a | 1977 | $memParams['membership_activity_status'] = ($pending || $isPayLater) ? 'Scheduled' : 'Completed'; |
c98997b9 EM |
1978 | } |
1979 | //CRM-4555 | |
1980 | if ($pending) { | |
1981 | $updateStatusId = array_search('Pending', $allStatus); | |
1982 | } | |
1983 | } | |
1984 | else { | |
1985 | // NEW Membership | |
c98997b9 EM |
1986 | $memParams = array( |
1987 | 'contact_id' => $contactID, | |
1988 | 'membership_type_id' => $membershipTypeID, | |
1989 | ); | |
1990 | ||
1991 | if (!$pending) { | |
1992 | $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms); | |
1993 | ||
620ce374 | 1994 | foreach (array('join_date', 'start_date', 'end_date') as $dateType) { |
1995 | $memParams[$dateType] = CRM_Utils_Array::value($dateType, $formDates); | |
1996 | if (empty($memParams[$dateType])) { | |
1997 | $memParams[$dateType] = CRM_Utils_Array::value($dateType, $dates); | |
1998 | } | |
1999 | } | |
c98997b9 EM |
2000 | |
2001 | $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'], | |
2002 | $statusFormat | |
2003 | ), | |
2004 | CRM_Utils_Date::customFormat($dates['end_date'], | |
2005 | $statusFormat | |
2006 | ), | |
2007 | CRM_Utils_Date::customFormat($dates['join_date'], | |
2008 | $statusFormat | |
2009 | ), | |
2010 | 'today', | |
2011 | TRUE, | |
2012 | $membershipTypeID, | |
2013 | $memParams | |
2014 | ); | |
2015 | $updateStatusId = CRM_Utils_Array::value('id', $status); | |
2016 | } | |
2017 | else { | |
2018 | // if IPN/Pay-Later set status to: PENDING | |
2019 | $updateStatusId = array_search('Pending', $allStatus); | |
2020 | } | |
2021 | ||
2022 | if (!empty($membershipSource)) { | |
2023 | $memParams['source'] = $membershipSource; | |
2024 | } | |
c98997b9 EM |
2025 | $memParams['is_test'] = $is_test; |
2026 | $memParams['is_pay_later'] = $isPayLater; | |
2027 | } | |
14065266 | 2028 | // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but |
2029 | // perhaps shouldn't be? | |
2030 | if ($contributionRecurID) { | |
2031 | $memParams['contribution_recur_id'] = $contributionRecurID; | |
2032 | } | |
c98997b9 EM |
2033 | //CRM-4555 |
2034 | //if we decided status here and want to skip status | |
2035 | //calculation in create( ); then need to pass 'skipStatusCal'. | |
2036 | if ($updateStatusId) { | |
2037 | $memParams['status_id'] = $updateStatusId; | |
2038 | $memParams['skipStatusCal'] = TRUE; | |
2039 | } | |
2040 | ||
2041 | //since we are renewing, | |
2042 | //make status override false. | |
2043 | $memParams['is_override'] = FALSE; | |
2044 | ||
2045 | //CRM-4027, create log w/ individual contact. | |
2046 | if ($modifiedID) { | |
2047 | $ids['userId'] = $modifiedID; | |
2048 | $memParams['is_for_organization'] = TRUE; | |
2049 | } | |
2050 | else { | |
2051 | $ids['userId'] = $contactID; | |
2052 | } | |
2053 | ||
2054 | //inherit campaign from contrib page. | |
2055 | if (isset($campaignId)) { | |
2056 | $memParams['campaign_id'] = $campaignId; | |
2057 | } | |
2058 | ||
356bfcaf | 2059 | $memParams['contribution'] = $contribution; |
c98997b9 | 2060 | $memParams['custom'] = $customFieldsFormatted; |
13a16f43 | 2061 | // Load all line items & process all in membership. Don't do in contribution. |
2062 | // Relevant tests in api_v3_ContributionPageTest. | |
2063 | $memParams['line_item'] = $lineItems; | |
d2460a89 | 2064 | $membership = self::create($memParams, $ids, FALSE); |
c98997b9 EM |
2065 | |
2066 | // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010 | |
2067 | // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072 | |
2068 | $membership->find(TRUE); | |
2069 | ||
2070 | return array($membership, $renewalMode, $dates); | |
2071 | } | |
2072 | ||
27b6ce36 EM |
2073 | /** |
2074 | * Get line items representing the default price set. | |
2075 | * | |
2076 | * @param int $membershipOrg | |
2077 | * @param int $membershipTypeID | |
2078 | * @param float $total_amount | |
ccb02c2d | 2079 | * @param int $priceSetId |
27b6ce36 EM |
2080 | * |
2081 | * @return array | |
2082 | */ | |
ccb02c2d | 2083 | public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) { |
27b6ce36 EM |
2084 | $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); |
2085 | ||
2086 | // The name of the price field corresponds to the membership_type organization contact. | |
2087 | $params = array( | |
2088 | 'price_set_id' => $priceSetId, | |
2089 | 'name' => $membershipOrg, | |
2090 | ); | |
2091 | $results = array(); | |
2092 | CRM_Price_BAO_PriceField::retrieve($params, $results); | |
2093 | ||
2094 | if (!empty($results)) { | |
2095 | $fields[$results['id']] = $priceSets['fields'][$results['id']]; | |
2096 | $fid = $results['id']; | |
2097 | $editedFieldParams = array( | |
2098 | 'price_field_id' => $results['id'], | |
2099 | 'membership_type_id' => $membershipTypeID, | |
2100 | ); | |
2101 | $results = array(); | |
2102 | CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $results); | |
2103 | $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']]; | |
2104 | if (!empty($total_amount)) { | |
2105 | $fields[$fid]['options'][$results['id']]['amount'] = $total_amount; | |
2106 | } | |
2107 | } | |
2108 | ||
2109 | $fieldID = key($fields); | |
2110 | $returnParams = array( | |
2111 | 'price_set_id' => $priceSetId, | |
2112 | 'price_sets' => $priceSets, | |
2113 | 'fields' => $fields, | |
2114 | 'price_fields' => array( | |
2115 | 'price_' . $fieldID => CRM_Utils_Array::value('id', $results), | |
b6924651 | 2116 | ), |
27b6ce36 EM |
2117 | ); |
2118 | return $returnParams; | |
2119 | } | |
2120 | ||
a392809d JV |
2121 | /** |
2122 | * Update the status of all deceased members to deceased. | |
2123 | * | |
2124 | * @return int | |
2125 | * Count of updated contacts. | |
2126 | */ | |
2127 | protected static function updateDeceasedMembersStatuses() { | |
2128 | $count = 0; | |
acd68908 OT |
2129 | |
2130 | $deceasedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased'); | |
2131 | ||
a392809d JV |
2132 | // 'create' context for buildOptions returns only if enabled. |
2133 | $allStatus = self::buildOptions('status_id', 'create'); | |
acd68908 | 2134 | if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) { |
a392809d JV |
2135 | // Deceased status is an admin status & is required. We want to fail early if |
2136 | // it is not present or active. | |
2137 | // We could make the case 'some databases just don't use deceased so we will check | |
2138 | // for the presence of a deceased contact in the DB before rejecting. | |
2139 | if (CRM_Core_DAO::singleValueQuery(' | |
2140 | SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0' | |
2141 | )) { | |
2142 | throw new CRM_Core_Exception( | |
2143 | ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.", | |
2144 | [1 => CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1')] | |
2145 | )); | |
2146 | } | |
2147 | } | |
2148 | $deceasedDAO = CRM_Core_DAO::executeQuery( | |
2149 | $baseQuery = " | |
2150 | SELECT membership.id as membership_id | |
2151 | FROM civicrm_membership membership | |
2152 | INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id | |
2153 | INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id | |
2154 | AND civicrm_membership_type.is_active = 1 | |
2155 | WHERE membership.is_test = 0 | |
2156 | AND civicrm_contact.is_deceased = 1 | |
2157 | AND membership.status_id <> %1 | |
2158 | ", | |
2159 | [1 => [$deceasedStatusId, 'Integer']] | |
2160 | ); | |
2161 | while ($deceasedDAO->fetch()) { | |
2162 | civicrm_api3('membership', 'create', [ | |
2163 | 'id' => $deceasedDAO->membership_id, | |
2164 | 'status_id' => $deceasedStatusId, | |
2165 | 'createActivity' => TRUE, | |
2166 | 'skipStatusCal' => TRUE, | |
2167 | 'skipRecentView' => TRUE, | |
2168 | ]); | |
2169 | $count++; | |
2170 | } | |
2171 | $deceasedDAO->free(); | |
2172 | return $count; | |
2173 | } | |
2174 | ||
6a488035 | 2175 | /** |
100fef9d | 2176 | * Process price set and line items. |
6a488035 | 2177 | * |
100fef9d | 2178 | * @param int $membershipId |
7b835f7c | 2179 | * @param array $lineItem |
6a488035 | 2180 | */ |
00be9182 | 2181 | public function processPriceSet($membershipId, $lineItem) { |
6a488035 TO |
2182 | //FIXME : need to move this too |
2183 | if (!$membershipId || !is_array($lineItem) | |
ca58d9b9 | 2184 | || CRM_Utils_System::isNull($lineItem) |
6a488035 TO |
2185 | ) { |
2186 | return; | |
2187 | } | |
2188 | ||
2189 | foreach ($lineItem as $priceSetId => $values) { | |
2190 | if (!$priceSetId) { | |
2191 | continue; | |
2192 | } | |
2193 | foreach ($values as $line) { | |
2194 | $line['entity_table'] = 'civicrm_membership'; | |
2195 | $line['entity_id'] = $membershipId; | |
2196 | CRM_Price_BAO_LineItem::create($line); | |
2197 | } | |
2198 | } | |
2199 | } | |
2200 | ||
2201 | /** | |
fe482240 | 2202 | * Retrieve the contribution id for the associated Membership id. |
ca266339 | 2203 | * @todo we should get this off the line item |
6a488035 | 2204 | * |
b2363ea8 TO |
2205 | * @param int $membershipId |
2206 | * Membership id. | |
fde55343 JP |
2207 | * @all bool |
2208 | * if more than one payment associated with membership id need to be returned. | |
6a488035 | 2209 | * |
81716ddb | 2210 | * @return int|int[] |
a6c01b45 | 2211 | * contribution id |
6a488035 | 2212 | */ |
fde55343 | 2213 | public static function getMembershipContributionId($membershipId, $all = FALSE) { |
6a488035 | 2214 | |
ca266339 EM |
2215 | $membershipPayment = new CRM_Member_DAO_MembershipPayment(); |
2216 | $membershipPayment->membership_id = $membershipId; | |
fde55343 JP |
2217 | if ($all && $membershipPayment->find()) { |
2218 | $contributionIds = array(); | |
2219 | while ($membershipPayment->fetch()) { | |
2220 | $contributionIds[] = $membershipPayment->contribution_id; | |
2221 | } | |
2222 | return $contributionIds; | |
2223 | } | |
2224 | ||
ca266339 EM |
2225 | if ($membershipPayment->find(TRUE)) { |
2226 | return $membershipPayment->contribution_id; | |
6a488035 TO |
2227 | } |
2228 | return NULL; | |
2229 | } | |
2230 | ||
2231 | /** | |
e0556ebe TO |
2232 | * The function checks and updates the status of all membership records for a given domain using the |
2233 | * calc_membership_status and update_contact_membership APIs. | |
2234 | * | |
2235 | * IMPORTANT: | |
2236 | * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3. | |
2237 | * | |
a6c01b45 | 2238 | * @return array |
e0556ebe | 2239 | */ |
00be9182 | 2240 | public static function updateAllMembershipStatus() { |
a392809d JV |
2241 | // Tests for this function are in api_v3_JobTest. Please add tests for all updates. |
2242 | ||
2243 | $updateCount = $processCount = self::updateDeceasedMembersStatuses(); | |
354ee85e | 2244 | $allStatus = CRM_Member_PseudoConstant::membershipStatus(); |
e0556ebe | 2245 | $allTypes = CRM_Member_PseudoConstant::membershipType(); |
6a488035 | 2246 | |
a392809d JV |
2247 | // This query retrieves ALL memberships of active types. |
2248 | $baseQuery = " | |
6a488035 TO |
2249 | SELECT civicrm_membership.id as membership_id, |
2250 | civicrm_membership.is_override as is_override, | |
e136f704 | 2251 | civicrm_membership.status_override_end_date as status_override_end_date, |
6a488035 TO |
2252 | civicrm_membership.membership_type_id as membership_type_id, |
2253 | civicrm_membership.status_id as status_id, | |
2254 | civicrm_membership.join_date as join_date, | |
2255 | civicrm_membership.start_date as start_date, | |
2256 | civicrm_membership.end_date as end_date, | |
2257 | civicrm_membership.source as source, | |
2258 | civicrm_contact.id as contact_id, | |
6a488035 TO |
2259 | civicrm_membership.owner_membership_id as owner_membership_id, |
2260 | civicrm_membership.contribution_recur_id as recur_id | |
2261 | FROM civicrm_membership | |
2262 | INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id ) | |
85b6e9a2 DL |
2263 | INNER JOIN civicrm_membership_type ON |
2264 | (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1) | |
354ee85e J |
2265 | WHERE civicrm_membership.is_test = 0 |
2266 | AND civicrm_contact.is_deceased = 0 "; | |
2267 | ||
2268 | $deceaseStatusId = array_search('Deceased', $allStatus); | |
2269 | $pendingStatusId = array_search('Pending', $allStatus); | |
2270 | // CRM-15475 | |
2271 | $cancelledStatusId = array_search( | |
2272 | 'Cancelled', | |
2273 | CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE) | |
2274 | ); | |
2275 | $expiredStatusId = array_search('Expired', $allStatus); | |
6a488035 | 2276 | |
354ee85e J |
2277 | $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL"; |
2278 | $dao1 = CRM_Core_DAO::executeQuery($query); | |
2279 | while ($dao1->fetch()) { | |
2280 | self::processOverriddenUntilDateMembership($dao1); | |
2281 | } | |
2282 | $dao1->free(); | |
6a488035 | 2283 | |
354ee85e J |
2284 | $query = $baseQuery . " AND civicrm_membership.is_override IS NULL |
2285 | AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4) | |
2286 | AND civicrm_membership.owner_membership_id IS NULL "; | |
2287 | $params = array( | |
2288 | 1 => array($pendingStatusId, 'Integer'), | |
2289 | 2 => array($cancelledStatusId, 'Integer'), | |
2290 | 3 => array($expiredStatusId, 'Integer'), | |
2291 | 4 => array($deceaseStatusId, 'Integer'), | |
2292 | ); | |
2293 | $dao2 = CRM_Core_DAO::executeQuery($query, $params); | |
2294 | ||
2295 | while ($dao2->fetch()) { | |
2296 | // echo "."; | |
6a488035 TO |
2297 | $processCount++; |
2298 | ||
354ee85e | 2299 | // Put common parameters into array for easy access |
6a488035 | 2300 | $memberParams = array( |
354ee85e J |
2301 | 'id' => $dao2->membership_id, |
2302 | 'status_id' => $dao2->status_id, | |
2303 | 'contact_id' => $dao2->contact_id, | |
2304 | 'membership_type_id' => $dao2->membership_type_id, | |
2305 | 'membership_type' => $allTypes[$dao2->membership_type_id], | |
2306 | 'join_date' => $dao2->join_date, | |
2307 | 'start_date' => $dao2->start_date, | |
2308 | 'end_date' => $dao2->end_date, | |
2309 | 'source' => $dao2->source, | |
6a488035 TO |
2310 | 'skipStatusCal' => TRUE, |
2311 | 'skipRecentView' => TRUE, | |
2312 | ); | |
2313 | ||
354ee85e J |
2314 | // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses |
2315 | //get the membership status as per id. | |
2316 | $newStatus = civicrm_api('membership_status', 'calc', | |
2317 | array( | |
2318 | 'membership_id' => $dao2->membership_id, | |
2319 | 'version' => 3, | |
2320 | 'ignore_admin_only' => TRUE, | |
2321 | ), TRUE | |
2322 | ); | |
2323 | $statusId = CRM_Utils_Array::value('id', $newStatus); | |
6a488035 | 2324 | |
354ee85e J |
2325 | //process only when status change. |
2326 | if ($statusId && | |
2327 | $statusId != $dao2->status_id | |
6a488035 | 2328 | ) { |
354ee85e J |
2329 | //take all params that need to save. |
2330 | $memParams = $memberParams; | |
2331 | $memParams['status_id'] = $statusId; | |
2332 | $memParams['createActivity'] = TRUE; | |
2333 | $memParams['version'] = 3; | |
2334 | ||
2335 | // Unset columns which should remain unchanged from their current saved | |
2336 | // values. This avoids race condition in which these values may have | |
2337 | // been changed by other processes. | |
2338 | unset( | |
2339 | $memParams['contact_id'], | |
2340 | $memParams['membership_type_id'], | |
2341 | $memParams['membership_type'], | |
2342 | $memParams['join_date'], | |
2343 | $memParams['start_date'], | |
2344 | $memParams['end_date'], | |
2345 | $memParams['source'] | |
6a488035 | 2346 | ); |
354ee85e | 2347 | //since there is change in status. |
6a488035 | 2348 | |
354ee85e J |
2349 | //process member record. |
2350 | civicrm_api('membership', 'create', $memParams); | |
2351 | $updateCount++; | |
6a488035 | 2352 | } |
6a488035 | 2353 | } |
354ee85e | 2354 | $dao2->free(); |
6a488035 | 2355 | $result['is_error'] = 0; |
e0556ebe | 2356 | $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array( |
353ffa53 TO |
2357 | 1 => $processCount, |
2358 | 2 => $updateCount, | |
2359 | )); | |
6a488035 TO |
2360 | return $result; |
2361 | } | |
2362 | ||
e136f704 O |
2363 | /** |
2364 | * Set is_override for the 'overridden until date' membership to | |
2365 | * False and clears the 'until date' field in case the 'until date' | |
2366 | * is equal or after today date. | |
2367 | * | |
2368 | * @param CRM_Core_DAO $membership | |
2369 | * The membership to be processed | |
2370 | */ | |
2371 | private static function processOverriddenUntilDateMembership($membership) { | |
2372 | $isOverriddenUntilDate = !empty($membership->is_override) && !empty($membership->status_override_end_date); | |
2373 | if (!$isOverriddenUntilDate) { | |
2374 | return; | |
2375 | } | |
2376 | ||
2377 | $todayDate = new DateTime(); | |
2378 | $todayDate->setTime(0, 0); | |
2379 | ||
2380 | $overrideEndDate = new DateTime($membership->status_override_end_date); | |
2381 | $overrideEndDate->setTime(0, 0); | |
2382 | ||
2383 | $datesDifference = $todayDate->diff($overrideEndDate); | |
2384 | $daysDifference = (int) $datesDifference->format('%R%a'); | |
2385 | if ($daysDifference <= 0) { | |
2386 | $params = array( | |
2387 | 'id' => $membership->membership_id, | |
2388 | 'is_override' => FALSE, | |
2389 | 'status_override_end_date' => 'null', | |
2390 | ); | |
2391 | civicrm_api3('membership', 'create', $params); | |
2392 | } | |
2393 | } | |
2394 | ||
e46e9a0b | 2395 | /** |
688d37c6 | 2396 | * Returns the membership types for a particular contact |
6a488035 TO |
2397 | * who has lifetime membership without end date. |
2398 | * | |
100fef9d | 2399 | * @param int $contactID |
e46e9a0b EM |
2400 | * @param bool $isTest |
2401 | * @param bool $onlyLifeTime | |
6a488035 | 2402 | * |
e46e9a0b | 2403 | * @return array |
6a488035 | 2404 | */ |
00be9182 | 2405 | public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) { |
6a488035 TO |
2406 | $contactMembershipType = array(); |
2407 | if (!$contactID) { | |
2408 | return $contactMembershipType; | |
2409 | } | |
2410 | ||
e0556ebe | 2411 | $dao = new CRM_Member_DAO_Membership(); |
6a488035 TO |
2412 | $dao->contact_id = $contactID; |
2413 | $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus()); | |
2414 | $dao->whereAdd("status_id != $pendingStatusId"); | |
2415 | ||
2416 | if ($isTest) { | |
2417 | $dao->is_test = $isTest; | |
2418 | } | |
2419 | else { | |
2420 | $dao->whereAdd('is_test IS NULL OR is_test = 0'); | |
2421 | } | |
2422 | ||
2423 | if ($onlyLifeTime) { | |
2424 | $dao->whereAdd('end_date IS NULL'); | |
2425 | } | |
2426 | ||
2427 | $dao->find(); | |
2428 | while ($dao->fetch()) { | |
2429 | $membership = array(); | |
2430 | CRM_Core_DAO::storeValues($dao, $membership); | |
2431 | $contactMembershipType[$dao->membership_type_id] = $membership; | |
2432 | } | |
2433 | return $contactMembershipType; | |
2434 | } | |
2435 | ||
2436 | /** | |
fe482240 | 2437 | * Record contribution record associated with membership. |
6a488035 | 2438 | * |
b2363ea8 TO |
2439 | * @param array $params |
2440 | * Array of submitted params. | |
2441 | * @param array $ids | |
2442 | * (param in process of being removed - try to use params) array of ids. | |
6a488035 | 2443 | * |
02af3683 | 2444 | * @return CRM_Contribute_BAO_Contribution |
6a488035 | 2445 | */ |
e0556ebe | 2446 | public static function recordMembershipContribution(&$params, $ids = array()) { |
d824fb6e | 2447 | $membershipId = $params['membership_id']; |
6a488035 TO |
2448 | $contributionParams = array(); |
2449 | $config = CRM_Core_Config::singleton(); | |
2450 | $contributionParams['currency'] = $config->defaultCurrency; | |
2451 | $contributionParams['receipt_date'] = (CRM_Utils_Array::value('receipt_date', $params)) ? $params['receipt_date'] : 'null'; | |
2452 | $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params); | |
6a488035 | 2453 | $contributionParams['non_deductible_amount'] = 'null'; |
f8df19bb | 2454 | $contributionParams['skipCleanMoney'] = TRUE; |
dcb032dc | 2455 | $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor_id', $params); |
d80dbc14 | 2456 | $contributionSoftParams = CRM_Utils_Array::value('soft_credit', $params); |
6a488035 | 2457 | $recordContribution = array( |
e0556ebe | 2458 | 'contact_id', |
77623a96 | 2459 | 'fee_amount', |
e0556ebe TO |
2460 | 'total_amount', |
2461 | 'receive_date', | |
2462 | 'financial_type_id', | |
2463 | 'payment_instrument_id', | |
2464 | 'trxn_id', | |
2465 | 'invoice_id', | |
2466 | 'is_test', | |
2467 | 'contribution_status_id', | |
2468 | 'check_number', | |
2469 | 'campaign_id', | |
2470 | 'is_pay_later', | |
2471 | 'membership_id', | |
2472 | 'tax_amount', | |
21dfd5f5 | 2473 | 'skipLineItem', |
e136edcf | 2474 | 'contribution_recur_id', |
a55e39e9 | 2475 | 'pan_truncation', |
2476 | 'card_type_id', | |
6a488035 TO |
2477 | ); |
2478 | foreach ($recordContribution as $f) { | |
2479 | $contributionParams[$f] = CRM_Utils_Array::value($f, $params); | |
2480 | } | |
2481 | ||
2482 | // make entry in batch entity batch table | |
a7488080 | 2483 | if (!empty($params['batch_id'])) { |
6a488035 TO |
2484 | $contributionParams['batch_id'] = $params['batch_id']; |
2485 | } | |
2486 | ||
91ef9be0 | 2487 | if (!empty($params['contribution_contact_id'])) { |
2488 | // deal with possibility of a different person paying for contribution | |
2489 | $contributionParams['contact_id'] = $params['contribution_contact_id']; | |
2490 | } | |
2491 | ||
a7488080 | 2492 | if (!empty($params['processPriceSet']) && |
6a488035 TO |
2493 | !empty($params['lineItems']) |
2494 | ) { | |
2495 | $contributionParams['line_item'] = CRM_Utils_Array::value('lineItems', $params, NULL); | |
2496 | } | |
2497 | ||
2498 | $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); | |
2499 | ||
c206647d | 2500 | //CRM-13981, create new soft-credit record as to record payment from different person for this membership |
d80dbc14 | 2501 | if (!empty($contributionSoftParams)) { |
9e1854a1 | 2502 | if (!empty($params['batch_id'])) { |
2503 | foreach ($contributionSoftParams as $contributionSoft) { | |
2504 | $contributionSoft['contribution_id'] = $contribution->id; | |
2505 | $contributionSoft['currency'] = $contribution->currency; | |
2506 | CRM_Contribute_BAO_ContributionSoft::add($contributionSoft); | |
2507 | } | |
2508 | } | |
2509 | else { | |
e0556ebe TO |
2510 | $contributionSoftParams['contribution_id'] = $contribution->id; |
2511 | $contributionSoftParams['currency'] = $contribution->currency; | |
2512 | $contributionSoftParams['amount'] = $contribution->total_amount; | |
2513 | CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams); | |
a54e2c55 | 2514 | } |
d80dbc14 | 2515 | } |
2516 | ||
6a488035 TO |
2517 | // store contribution id |
2518 | $params['contribution_id'] = $contribution->id; | |
2519 | ||
6a488035 | 2520 | //insert payment record for this membership |
8cc574cf | 2521 | if (empty($ids['contribution']) || !empty($params['is_recur'])) { |
e0556ebe | 2522 | CRM_Member_BAO_MembershipPayment::create(array( |
353ffa53 TO |
2523 | 'membership_id' => $membershipId, |
2524 | 'contribution_id' => $contribution->id, | |
2525 | )); | |
6a488035 TO |
2526 | } |
2527 | return $contribution; | |
2528 | } | |
2529 | ||
e46e9a0b EM |
2530 | /** |
2531 | * @todo document me - I seem a bit out of date.... | |
2532 | */ | |
00be9182 | 2533 | public static function _getActTypes() { |
4e636a74 AH |
2534 | $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); |
2535 | self::$_renewalActType = CRM_Utils_Array::key('Membership Renewal', $activityTypes); | |
2536 | self::$_signupActType = CRM_Utils_Array::key('Membership Signup', $activityTypes); | |
2537 | } | |
5624f515 | 2538 | |
b5a62499 PN |
2539 | /** |
2540 | * Get all Cancelled Membership(s) for a contact | |
2541 | * | |
b2363ea8 TO |
2542 | * @param int $contactID |
2543 | * Contact id. | |
2544 | * @param bool $isTest | |
2545 | * Mode of payment. | |
b5a62499 | 2546 | * |
a6c01b45 | 2547 | * @return array |
16b10e64 | 2548 | * Array of membership type |
b5a62499 | 2549 | */ |
00be9182 | 2550 | public static function getContactsCancelledMembership($contactID, $isTest = FALSE) { |
b5a62499 PN |
2551 | if (!$contactID) { |
2552 | return array(); | |
5624f515 | 2553 | } |
b5a62499 PN |
2554 | $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3'; |
2555 | $queryParams = array( | |
2556 | 1 => array($contactID, 'Integer'), | |
7ff60806 PN |
2557 | 2 => array( |
2558 | // CRM-15475 | |
2559 | array_search( | |
4c16123d | 2560 | 'Cancelled', |
7ff60806 | 2561 | CRM_Member_PseudoConstant::membershipStatus( |
4c16123d EM |
2562 | NULL, |
2563 | " name = 'Cancelled' ", | |
2564 | 'name', | |
2565 | FALSE, | |
7ff60806 PN |
2566 | TRUE |
2567 | ) | |
4c16123d | 2568 | ), |
21dfd5f5 | 2569 | 'Integer', |
7ff60806 | 2570 | ), |
b5a62499 PN |
2571 | 3 => array($isTest, 'Boolean'), |
2572 | ); | |
5624f515 | 2573 | |
b5a62499 PN |
2574 | $dao = CRM_Core_DAO::executeQuery($query, $queryParams); |
2575 | $cancelledMembershipIds = array(); | |
2576 | while ($dao->fetch()) { | |
2577 | $cancelledMembershipIds[] = $dao->membership_type_id; | |
2578 | } | |
2579 | return $cancelledMembershipIds; | |
2580 | } | |
96025800 | 2581 | |
c31e68ae OT |
2582 | /** |
2583 | * Merges the memberships from otherContactID to mainContactID. | |
2584 | * | |
2585 | * General idea is to merge memberships in regards to their type. We | |
2586 | * move the other contact’s contributions to the main contact’s | |
2587 | * membership which has the same type (if any) and then we update | |
2588 | * membership to avoid loosing `join_date`, `end_date`, and | |
2589 | * `status_id`. In this function, we don’t touch the contributions | |
2590 | * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care | |
2591 | * of it). | |
2592 | * | |
2593 | * This function adds new SQL queries to the $sqlQueries parameter. | |
2594 | * | |
2595 | * @param int $mainContactID | |
2596 | * Contact id of main contact record. | |
2597 | * @param int $otherContactID | |
2598 | * Contact id of record which is going to merge. | |
2599 | * @param array $sqlQueries | |
2600 | * (reference) array of SQL queries to be executed. | |
2601 | * @param array $tables | |
2602 | * List of tables that have to be merged. | |
2603 | * @param array $tableOperations | |
2604 | * Special options/params for some tables to be merged. | |
2605 | * | |
2606 | * @see CRM_Dedupe_Merger::cpTables() | |
2607 | */ | |
2608 | public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) { | |
2609 | /* | |
2610 | * If the user requests not to merge memberships but to add them, | |
2611 | * just attribute the `civicrm_membership` to the | |
2612 | * `$mainContactID`. We have to do this here since the general | |
2613 | * merge process is bypassed by this function. | |
2614 | */ | |
2615 | if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) { | |
2616 | $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID"; | |
2617 | return; | |
2618 | } | |
2619 | ||
2620 | /* | |
2621 | * Retrieve all memberships that belongs to each contacts and | |
2622 | * keep track of each membership type. | |
2623 | */ | |
2624 | $mainContactMemberships = array(); | |
2625 | $otherContactMemberships = array(); | |
2626 | ||
2627 | $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1"; | |
2628 | $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($mainContactID, "Integer"))); | |
2629 | while ($dao->fetch()) { | |
2630 | $mainContactMemberships[$dao->id] = $dao->membership_type_id; | |
2631 | } | |
2632 | ||
2633 | $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($otherContactID, "Integer"))); | |
2634 | while ($dao->fetch()) { | |
2635 | $otherContactMemberships[$dao->id] = $dao->membership_type_id; | |
2636 | } | |
2637 | ||
2638 | /* | |
2639 | * For each membership, move related contributions to the main | |
2640 | * contact’s membership (by updating `membership_payments`). Then, | |
2641 | * update membership’s `join_date` (if the other membership’s | |
2642 | * join_date is older) and `end_date` (if the other membership’s | |
2643 | * `end_date` is newer) and `status_id` (if the newly calculated | |
2644 | * status is different). | |
2645 | * | |
2646 | * FIXME: what should we do if we have multiple memberships with | |
2647 | * the same type (currently we only take the first one)? | |
2648 | */ | |
2649 | $newSql = array(); | |
2650 | foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) { | |
2651 | if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) { | |
2652 | ||
2653 | /* | |
2654 | * Move other membership’s contributions to the main one only | |
2655 | * if user requested to merge contributions. | |
2656 | */ | |
2657 | if (!empty($tables) && in_array('civicrm_contribution', $tables)) { | |
2658 | $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId"; | |
2659 | } | |
2660 | ||
2661 | $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1"; | |
2662 | ||
2663 | $newMembership = CRM_Member_DAO_Membership::findById($newMembershipId); | |
2664 | $otherMembership = CRM_Member_DAO_Membership::findById($otherMembershipId); | |
2665 | ||
2666 | $updates = array(); | |
2667 | if (new DateTime($otherMembership->join_date) < new DateTime($newMembership->join_date)) { | |
2668 | $updates["join_date"] = $otherMembership->join_date; | |
2669 | } | |
2670 | ||
2671 | if (new DateTime($otherMembership->end_date) > new DateTime($newMembership->end_date)) { | |
2672 | $updates["end_date"] = $otherMembership->end_date; | |
2673 | } | |
2674 | ||
2675 | if (count($updates)) { | |
2676 | ||
2677 | /* | |
2678 | * Update status | |
2679 | */ | |
2680 | $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate( | |
2681 | isset($updates["start_date"]) ? $updates["start_date"] : $newMembership->start_date, | |
2682 | isset($updates["end_date"]) ? $updates["end_date"] : $newMembership->end_date, | |
2683 | isset($updates["join_date"]) ? $updates["join_date"] : $newMembership->join_date, | |
2684 | 'today', | |
2685 | FALSE, | |
2686 | $newMembershipId, | |
2687 | $newMembership | |
2688 | ); | |
2689 | ||
2690 | if (!empty($status['id']) and $status['id'] != $newMembership->status_id) { | |
2691 | $updates['status_id'] = $status['id']; | |
2692 | } | |
2693 | ||
2694 | $updates_sql = []; | |
2695 | foreach ($updates as $k => $v) { | |
2696 | $updates_sql[] = "$k = '{$v}'"; | |
2697 | } | |
2698 | ||
2699 | $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId); | |
2700 | $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId); | |
2701 | } | |
2702 | ||
2703 | } | |
2704 | } | |
2705 | ||
2706 | $sqlQueries = array_merge($sqlQueries, $newSql); | |
2707 | } | |
2708 | ||
6a488035 | 2709 | } |