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