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