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