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