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