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