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