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