3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class generates form components for offline membership form
40 class CRM_Member_Form_Membership
extends CRM_Member_Form
{
42 protected $_memType = NULL;
44 protected $_onlinePendingContributionId;
48 public $_contributeMode = 'direct';
50 protected $_recurMembershipTypes;
52 protected $_memTypeSelected;
55 * Display name of the member
57 protected $_memberDisplayName = NULL;
60 * email of the person paying for the membership (used for receipts)
62 protected $_memberEmail = NULL;
65 * Contact ID of the member
67 public $_contactID = NULL;
70 * Display name of the person paying for the membership (used for receipts)
72 protected $_contributorDisplayName = NULL;
75 * email of the person paying for the membership (used for receipts)
77 protected $_contributorEmail = NULL;
80 * email of the person paying for the membership (used for receipts)
82 protected $_contributorContactID = NULL;
85 * ID of the person the receipt is to go to
87 protected $_receiptContactId = NULL;
90 * Keep a class variable for ALL membeshipID's so
91 * postProcess hook function can do something with it
93 protected $_membershipIDs = array();
96 * An array to hold a list of datefields on the form
97 * so that they can be converted to ISO in a consistent manner
101 protected $_dateFields = array(
102 'receive_date' => array('default' => 'now'),
105 public function preProcess() {
106 //custom data related code
107 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
108 $this->assign('cdType', FALSE);
109 if ($this->_cdType
) {
110 $this->assign('cdType', TRUE);
111 return CRM_Custom_Form_CustomData
::preProcess($this);
114 parent
::preProcess();
116 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
117 $this->set('priceSetId', $this->_priceSetId
);
118 $this->assign('priceSetId', $this->_priceSetId
);
121 // check for edit permission
122 if (!CRM_Core_Permission
::checkActionPermission('CiviMember', $this->_action
)) {
123 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
126 if ($this->_action
& CRM_Core_Action
::DELETE
) {
127 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
128 // check delete permission for contribution
129 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
130 CRM_Core_Error
::fatal(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
134 if ($this->_action
& CRM_Core_Action
::ADD
) {
135 if (!CRM_Member_BAO_Membership
::statusAvailabilty($this->_contactID
)) {
136 // all possible statuses are disabled - redirect back to contact form
137 CRM_Core_Error
::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
140 if ($this->_contactID
) {
141 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
142 $contactMemberships = array();
143 $memParams = array('contact_id' => $this->_contactID
);
144 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
145 $cMemTypes = array();
146 foreach ($contactMemberships as $mem) {
147 $cMemTypes[] = $mem['membership_type_id'];
149 if (count($cMemTypes) > 0) {
150 $memberorgs = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($cMemTypes);
151 $mems_by_org = array();
152 foreach ($contactMemberships as $memid => $mem) {
153 $mem['member_of_contact_id'] = CRM_Utils_Array
::value($mem['membership_type_id'], $memberorgs);
154 if (!empty($mem['membership_end_date'])) {
155 $mem['membership_end_date'] = CRM_Utils_Date
::customformat($mem['membership_end_date']);
157 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
158 $mem['membership_type_id'],
161 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
165 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
166 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
167 . ($this->_mode ?
'&mode=live' : '')
169 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
170 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
172 $mems_by_org[$mem['member_of_contact_id']] = $mem;
174 $this->assign('existingContactMemberships', $mems_by_org);
178 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
179 $resources = CRM_Core_Resources
::singleton();
180 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
182 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
183 'memtypes' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'membership_type_id'),
184 'statuses' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'status_id'),
186 $resources->addSetting(array('existingMems' => $passthru));
190 // when custom data is included in this page
191 if (!empty($_POST['hidden_custom'])) {
192 CRM_Custom_Form_CustomData
::preProcess($this);
193 CRM_Custom_Form_CustomData
::buildQuickForm($this);
194 CRM_Custom_Form_CustomData
::setDefaultValues($this);
197 // CRM-4395, get the online pending contribution id.
198 $this->_onlinePendingContributionId
= NULL;
199 if (!$this->_mode
&& $this->_id
&& ($this->_action
& CRM_Core_Action
::UPDATE
)) {
200 $this->_onlinePendingContributionId
= CRM_Contribute_BAO_Contribution
::checkOnlinePendingContribution($this->_id
,
204 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId
);
206 $this->setPageTitle(ts('Membership'));
210 * Set default values for the form. MobileProvider that in edit/view mode
211 * the default values are retrieved from the database
217 public function setDefaultValues() {
218 if ($this->_cdType
) {
219 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
222 if ($this->_priceSetId
) {
223 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
226 $defaults = parent
::setDefaultValues();
228 //setting default join date and receive date
229 list($now, $currentTime) = CRM_Utils_Date
::setDateDefaults();
230 if ($this->_action
== CRM_Core_Action
::ADD
) {
231 $defaults['receive_date'] = $now;
232 $defaults['receive_date_time'] = $currentTime;
235 if (is_numeric($this->_memType
)) {
236 $defaults['membership_type_id'] = array();
237 $defaults['membership_type_id'][0] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
239 'member_of_contact_id',
242 $defaults['membership_type_id'][1] = $this->_memType
;
245 $defaults['membership_type_id'] = $this->_memType
;
248 $defaults['num_terms'] = 1;
250 if (!empty($defaults['id'])) {
251 if ($this->_onlinePendingContributionId
) {
252 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
255 $contributionId = CRM_Core_DAO
::singleValueQuery("
256 SELECT contribution_id
257 FROM civicrm_membership_payment
258 WHERE membership_id = $this->_id
259 ORDER BY contribution_id
262 if ($contributionId) {
263 $defaults['record_contribution'] = $contributionId;
268 //set Soft Credit Type to Gift by default
269 $scTypes = CRM_Core_OptionGroup
::values("soft_credit_type");
270 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
272 if (!empty($defaults['record_contribution']) && !$this->_mode
) {
273 $contributionParams = array('id' => $defaults['record_contribution']);
274 $contributionIds = array();
276 //keep main object campaign in hand.
277 $memberCampaignId = CRM_Utils_Array
::value('campaign_id', $defaults);
279 CRM_Contribute_BAO_Contribution
::getValues($contributionParams, $defaults, $contributionIds);
281 //get back original object campaign id.
282 $defaults['campaign_id'] = $memberCampaignId;
284 if (!empty($defaults['receive_date'])) {
285 list($defaults['receive_date']) = CRM_Utils_Date
::setDateDefaults($defaults['receive_date']);
288 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
289 if (!empty($defaults['membership_source'])) {
290 $defaults['source'] = $defaults['membership_source'];
294 if (empty($defaults['payment_instrument_id'])) {
295 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
298 // User must explicitly choose to send a receipt in both add and update mode.
299 $defaults['send_receipt'] = 0;
301 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
302 // in this mode by default uncheck this checkbox
303 unset($defaults['record_contribution']);
306 if (!empty($defaults['id'])) {
307 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
310 $alreadyAutoRenew = FALSE;
311 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
312 $defaults['auto_renew'] = 1;
313 $alreadyAutoRenew = TRUE;
315 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
317 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
319 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
321 if (!empty($defaults['is_pay_later'])) {
322 $this->assign('is_pay_later', TRUE);
325 // set default country from config if no country set
326 $config = CRM_Core_Config
::singleton();
327 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
328 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
331 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
332 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
335 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
336 $defaults = array_merge($defaults, $billingDefaults);
338 // // hack to simplify credit card entry for testing
339 // $defaults['credit_card_type'] = 'Visa';
340 // $defaults['credit_card_number'] = '4807731747657838';
341 // $defaults['cvv2'] = '000';
342 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
345 $dates = array('join_date', 'start_date', 'end_date');
346 foreach ($dates as $key) {
347 if (!empty($defaults[$key])) {
348 list($defaults[$key]) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults));
352 //setting default join date if there is no join date
353 if (empty($defaults['join_date'])) {
354 $defaults['join_date'] = $now;
357 if (!empty($defaults['membership_end_date'])) {
358 $this->assign('endDate', $defaults['membership_end_date']);
365 * Build the form object
370 public function buildQuickForm() {
371 if ($this->_cdType
) {
372 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
375 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
376 // build price set form.
377 $buildPriceSet = FALSE;
378 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
379 if (!empty($_POST['price_set_id'])) {
380 $buildPriceSet = TRUE;
382 $getOnlyPriceSetElements = TRUE;
383 if (!$this->_priceSetId
) {
384 $this->_priceSetId
= $_POST['price_set_id'];
385 $getOnlyPriceSetElements = FALSE;
388 $this->set('priceSetId', $this->_priceSetId
);
389 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
391 $optionsMembershipTypes = array();
392 foreach ($this->_priceSet
['fields'] as $pField) {
393 if (empty($pField['options'])) {
396 foreach ($pField['options'] as $opId => $opValues) {
397 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
401 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
403 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
404 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
406 // get only price set form elements.
407 if ($getOnlyPriceSetElements) {
412 // use to build form during form rule.
413 $this->assign('buildPriceSet', $buildPriceSet);
415 if ($this->_action
& CRM_Core_Action
::ADD
) {
416 $buildPriceSet = FALSE;
417 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
418 if (!empty($priceSets)) {
419 $buildPriceSet = TRUE;
422 if ($buildPriceSet) {
423 $this->add('select', 'price_set_id', ts('Choose price set'),
425 '' => ts('Choose price set')
427 NULL, array('onchange' => "buildAmount( this.value );")
430 $this->assign('hasPriceSets', $buildPriceSet);
433 //need to assign custom data type and subtype to the template
434 $this->assign('customDataType', 'Membership');
435 $this->assign('customDataSubType', $this->_memType
);
436 $this->assign('entityID', $this->_id
);
438 if ($this->_action
& CRM_Core_Action
::DELETE
) {
439 $this->addButtons(array(
442 'name' => ts('Delete'),
443 'spacing' => ' ',
448 'name' => ts('Cancel'),
455 if ($this->_context
== 'standalone') {
456 $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
459 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
461 $dao = new CRM_Member_DAO_MembershipType();
462 $dao->domain_id
= CRM_Core_Config
::domainID();
465 // retrieve all memberships
466 $allMemberships = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this);
468 $allMembershipInfo = $membershipType = array();
469 foreach ($allMemberships as $key => $values) {
470 if (!empty($values['is_active'])) {
471 $membershipType[$key] = CRM_Utils_Array
::value('name', $values);
472 if ($this->_mode
&& empty($values['minimum_fee'])) {
476 $memberOfContactId = CRM_Utils_Array
::value('member_of_contact_id', $values);
477 if (empty($selMemTypeOrg[$memberOfContactId])) {
478 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
484 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
486 if (empty($selOrgMemType[$memberOfContactId][$key])) {
487 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array
::value('name', $values);
491 // build membership info array, which is used when membership type is selected to:
492 // - set the payment information block
493 // - set the max related block
494 $allMembershipInfo[$key] = array(
495 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $values),
496 'total_amount' => CRM_Utils_Money
::format($values['minimum_fee'], NULL, '%a'),
497 'total_amount_numeric' => CRM_Utils_Array
::value('minimum_fee', $values),
498 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $values),
499 'has_related' => isset($values['relationship_type_id']),
500 'max_related' => CRM_Utils_Array
::value('max_related', $values),
505 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
507 // show organization by default, if only one organization in
509 if (count($selMemTypeOrg) == 2) {
510 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
512 //sort membership organization and type, CRM-6099
513 natcasesort($selMemTypeOrg);
514 foreach ($selOrgMemType as $index => $orgMembershipType) {
515 natcasesort($orgMembershipType);
516 $selOrgMemType[$index] = $orgMembershipType;
519 $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
521 //build the form for auto renew.
522 $recurProcessor = $autoRenew = array();
523 if ($this->_mode ||
($this->_action
& CRM_Core_Action
::UPDATE
)) {
524 $autoRenewElement = $this->addElement('checkbox',
526 ts('Membership renewed automatically'),
528 array('onclick' => "buildReceiptANDNotice( );")
532 //get the valid recurring processors.
533 $recurring = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
534 $recurProcessor = array_intersect_assoc($this->_processors
, $recurring);
535 $autoRenew = array();
536 if (!empty($recurProcessor)) {
537 if (!empty($membershipType)) {
543 FROM civicrm_membership_type
544 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
545 $recurMembershipTypes = CRM_Core_DAO
::executeQuery($sql);
546 while ($recurMembershipTypes->fetch()) {
547 $autoRenew[$recurMembershipTypes->id
] = $recurMembershipTypes->auto_renew
;
554 $this->_recurMembershipTypes
[$recurMembershipTypes->id
][$fld] = $recurMembershipTypes->$fld;
560 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
565 $allowAutoRenew = FALSE;
566 if ($this->_mode
&& !empty($recurProcessor)) {
567 $allowAutoRenew = TRUE;
569 $this->assign('allowAutoRenew', $allowAutoRenew);
570 $this->assign('autoRenewOptions', json_encode($autoRenew));
571 $this->assign('recurProcessor', json_encode($recurProcessor));
573 // for max_related: a little JS to show/hide & set default value
574 $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
575 $this->add('text', 'max_related', ts('Max related'),
576 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
579 $sel = & $this->addElement('hierselect',
580 'membership_type_id',
581 ts('Membership Organization and Type'),
585 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
591 $this->applyFilter('__ALL__', 'trim');
593 if ($this->_action
& CRM_Core_Action
::ADD
) {
594 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
597 $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
598 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
599 $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
601 $elements[] = $endDate;
604 $this->add('text', 'source', ts('Source'),
605 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
608 //CRM-7362 --add campaigns.
611 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
613 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
616 $this->add('select', 'status_id', ts('Membership Status'),
617 array('' => ts('- select -')) + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
619 $statusOverride = $this->addElement('checkbox', 'is_override',
620 ts('Status Override?'), NULL,
621 array('onClick' => 'showHideMemberStatus()')
623 if ($statusOverride) {
624 $elements[] = $statusOverride;
627 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
629 $this->add('text', 'total_amount', ts('Amount'));
630 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
632 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
634 $this->add('select', 'payment_instrument_id',
636 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
637 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
639 $this->add('text', 'trxn_id', ts('Transaction ID'));
640 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
641 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id
, 'trxn_id')
644 $allowStatuses = array();
645 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
646 if ($this->_onlinePendingContributionId
) {
647 $statusNames = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
648 foreach ($statusNames as $val => $name) {
649 if (in_array($name, array(
656 $allowStatuses[$val] = $statuses[$val];
660 $allowStatuses = $statuses;
662 $this->add('select', 'contribution_status_id',
663 ts('Payment Status'), $allowStatuses
665 $this->add('text', 'check_number', ts('Check Number'),
666 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
670 //add field for amount to allow an amount to be entered that differs from minimum
671 $this->add('text', 'total_amount', ts('Amount'));
673 $this->add('select', 'financial_type_id',
674 ts('Financial Type'),
675 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType()
678 //CRM-10223 - allow contribution to be recorded against different contact
679 // causes a conflict in standalone mode so skip in standalone for now
680 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
681 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
682 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
685 $this->addElement('checkbox',
687 ts('Send Confirmation and Receipt?'), NULL,
688 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);")
691 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
693 $this->add('textarea', 'receipt_text_signup', ts('Receipt Message'));
695 // Retrieve the name and email of the contact - this will be the TO for receipt email
696 if ($this->_contactID
) {
697 list($this->_memberDisplayName
,
699 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
701 $this->assign('emailExists', $this->_memberEmail
);
702 $this->assign('displayName', $this->_memberDisplayName
);
706 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
707 $recurContributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
,
708 'contribution_recur_id'
710 if ($recurContributionId && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
)) {
712 if (CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
713 $this->assign('cancelAutoRenew',
714 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
717 foreach ($elements as $elem) {
722 $this->assign('isRecur', $isRecur);
724 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
726 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
729 $this->assign('outBound_option', $mailingInfo['outBound_option']);
731 parent
::buildQuickForm();
737 * @param array $params (ref.) an assoc array of name/value pairs
742 * @throws CiviCRM_API3_Exception
743 * @return mixed true or array of errors
747 static function formRule($params, $files, $self) {
750 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
753 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
755 $priceFieldIDS = array();
756 foreach ($self->_priceSet
['fields'] as $priceIds => $dontCare) {
758 if (!empty($params['price_' . $priceIds])) {
759 if (is_array($params['price_' . $priceIds])) {
760 foreach ($params['price_' . $priceIds] as $priceFldVal => $isSet) {
762 $priceFieldIDS[] = $priceFldVal;
767 $priceFieldIDS[] = $params['price_' . $priceIds];
772 if (!empty($priceFieldIDS)) {
773 $ids = implode(',', $priceFieldIDS);
775 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
776 foreach ($count as $id => $occurance) {
777 if ($occurance > 1) {
778 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
782 foreach ($priceFieldIDS as $priceFieldId) {
783 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
784 $self->_memTypeSelected
[$id] = $id;
789 elseif (empty($params['membership_type_id'][1])) {
790 $errors['membership_type_id'] = ts('Please select a membership type.');
793 $self->_memTypeSelected
[] = $params['membership_type_id'][1];
797 $numterms = CRM_Utils_Array
::value('num_terms', $params);
798 if ($numterms && intval($numterms) != $numterms) {
799 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
803 // Return error if empty $self->_memTypeSelected
804 if ($priceSetId && empty($errors) && empty($self->_memTypeSelected
)) {
805 $errors['_qf_default'] = ts('Select at least one membership option.');
808 if (!empty($errors) && (count($self->_memTypeSelected
) > 1)) {
809 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($self->_memTypeSelected
);
810 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
811 foreach ($duplicateMemberOfContacts as $countDuplicate) {
812 if ($countDuplicate > 1) {
813 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
818 if (!empty($errors)) {
822 if ($priceSetId && !$self->_mode
&& empty($params['record_contribution'])) {
823 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
826 if (!$priceSetId && $self->_mode
&& empty($params['financial_type_id'])) {
827 $errors['financial_type_id'] = ts('Please enter the financial Type.');
830 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
831 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
834 if (!empty($params['is_different_contribution_contact'])) {
835 if (empty($params['soft_credit_type_id'])) {
836 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
838 if (empty($params['soft_credit_contact_id'])) {
839 $errors['soft_credit_contact_id'] = ts('Please select a contact');
843 if (!empty($params['payment_processor_id'])) {
844 // make sure that credit card number and cvv are valid
845 CRM_Core_Payment_Form
::validateCreditCard($params, $errors);
849 if (!empty($params['join_date'])) {
851 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
853 foreach ($self->_memTypeSelected
as $memType) {
855 if (!empty($params['start_date'])) {
856 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
859 // if end date is set, ensure that start date is also set
860 // and that end date is later than start date
862 if (!empty($params['end_date'])) {
863 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
866 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
868 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) == 'rolling') {
869 if ($startDate < $joinDate) {
870 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
875 if ($membershipDetails['duration_unit'] == 'lifetime') {
876 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
877 // process to update status based on end-date. The user must change the status now.
878 $result = civicrm_api3('MembershipStatus', 'get', array(
880 'is_current_member' => 0,
882 $tmp_statuses = $result['values'];
883 $status_ids = array();
884 foreach($tmp_statuses as $cur_stat) {
885 $status_ids[] = $cur_stat['id'];
887 if (empty($params['status_id']) ||
in_array( $params['status_id'] , $status_ids) == false) {
888 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
889 $errors['is_override'] = ts('This must be checked because you set an End Date for a lifetime membership');
894 $errors['start_date'] = ts('Start date must be set if end date is set.');
896 if ($endDate < $startDate) {
897 $errors['end_date'] = ts('End date must be the same or later than start date.');
902 // Default values for start and end dates if not supplied
904 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
911 $startDate = CRM_Utils_Array
::value('start_date',
916 $endDate = CRM_Utils_Array
::value('end_date',
921 //CRM-3724, check for availability of valid membership status.
922 if (empty($params['is_override']) && !isset($errors['_qf_default'])) {
923 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
931 if (empty($calcStatus)) {
932 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
933 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
934 $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', array(1 => $url));
936 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
938 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
944 $errors['join_date'] = ts('Please enter the Member Since.');
947 if (isset($params['is_override']) &&
948 $params['is_override'] && empty($params['status_id'])) {
949 $errors['status_id'] = ts('Please enter the status.');
952 //total amount condition arise when membership type having no
954 if (isset($params['record_contribution'])) {
955 if (!$params['financial_type_id']) {
956 $errors['financial_type_id'] = ts('Please enter the financial Type.');
958 if (CRM_Utils_System
::isNull($params['total_amount'])) {
959 $errors['total_amount'] = ts('Please enter the contribution.');
963 // validate contribution status for 'Failed'.
964 if ($self->_onlinePendingContributionId
&& !empty($params['record_contribution']) &&
965 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
966 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
969 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
972 return empty($errors) ?
TRUE : $errors;
976 * Process the form submission
982 public function postProcess() {
983 if ($this->_action
& CRM_Core_Action
::DELETE
) {
984 CRM_Member_BAO_Membership
::del($this->_id
);
988 $isTest = ($this->_mode
== 'test') ?
1 : 0;
991 if (!empty($this->_lineItem
)) {
992 $lineItems = $this->_lineItem
;
995 $config = CRM_Core_Config
::singleton();
996 // get the submitted form values.
997 $this->_params
= $formValues = $this->controller
->exportValues($this->_name
);
998 $this->convertDateFieldsToMySQL($formValues);
1000 $params = $softParams = $ids = array();
1002 $membershipTypeValues = array();
1003 foreach ($this->_memTypeSelected
as $memType) {
1004 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1007 //take the required membership recur values.
1008 if ($this->_mode
&& !empty($this->_params
['auto_renew'])) {
1009 $params['is_recur'] = $this->_params
['is_recur'] = $formValues['is_recur'] = TRUE;
1011 'frequency_interval' => 'duration_interval',
1012 'frequency_unit' => 'duration_unit',
1016 foreach ($this->_memTypeSelected
as $memType) {
1017 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1018 $this->_recurMembershipTypes
, array()
1020 foreach ($mapping as $mapVal => $mapParam) {
1021 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array
::value($mapParam,
1022 $recurMembershipTypeValues
1025 $this->_params
[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1026 $recurMembershipTypeValues
1033 // unset send-receipt option, since receipt will be sent when ipn is received.
1034 unset($this->_params
['send_receipt'], $formValues['send_receipt']);
1037 // process price set and get total amount and line items.
1038 $lineItem = array();
1040 if (!$priceSetId = CRM_Utils_Array
::value('price_set_id', $formValues)) {
1041 CRM_Member_BAO_Membership
::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
1044 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1048 $termsByType = array();
1050 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1051 $this->_params
, $lineItem[$priceSetId]);
1052 if (CRM_Utils_Array
::value('tax_amount', $this->_params
)) {
1053 $params['tax_amount'] = $this->_params
['tax_amount'];
1055 $params['total_amount'] = CRM_Utils_Array
::value('amount', $this->_params
);
1056 $submittedFinancialType = CRM_Utils_Array
::value('financial_type_id', $formValues);
1057 if (!empty($lineItem[$priceSetId])) {
1058 foreach ($lineItem[$priceSetId] as &$li) {
1059 if (!empty($li['membership_type_id'])) {
1060 if (!empty($li['membership_num_terms'])) {
1061 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1065 ///CRM-11529 for quick config backoffice transactions
1066 //when financial_type_id is passed in form, update the
1067 //lineitems with the financial type selected in form
1068 if ($isQuickConfig && $submittedFinancialType) {
1069 $li['financial_type_id'] = $submittedFinancialType;
1075 $this->storeContactFields($formValues);
1077 $params['contact_id'] = $this->_contactID
;
1086 foreach ($fields as $f) {
1087 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1091 // when is_override false ignore is_admin statuses during membership
1092 // status calculation. similarly we did fix for import in CRM-3570.
1093 if (empty($params['is_override'])) {
1094 $params['exclude_is_admin'] = TRUE;
1097 // process date params to mysql date format.
1099 'join_date' => 'joinDate',
1100 'start_date' => 'startDate',
1101 'end_date' => 'endDate',
1103 foreach ($dateTypes as $dateField => $dateVariable) {
1104 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1107 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1109 $calcDates = array();
1110 foreach ($this->_memTypeSelected
as $memType) {
1111 if (empty($memTypeNumTerms)) {
1112 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1114 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1115 $joinDate, $startDate, $endDate, $memTypeNumTerms
1119 foreach ($calcDates as $memType => $calcDate) {
1120 foreach (array_keys($dateTypes) as $d) {
1121 //first give priority to form values then calDates.
1122 $date = CRM_Utils_Array
::value($d, $formValues);
1124 $date = CRM_Utils_Array
::value($d, $calcDate);
1127 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1128 //$params[$d] = CRM_Utils_Date::processDate( $date );
1132 // max related memberships - take from form or inherit from membership type
1133 foreach ($this->_memTypeSelected
as $memType) {
1134 if (array_key_exists('max_related', $formValues)) {
1135 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array
::value('max_related', $formValues);
1140 $ids['membership'] = $params['id'] = $this->_id
;
1143 $session = CRM_Core_Session
::singleton();
1144 $ids['userId'] = $session->get('userID');
1146 // membership type custom data
1147 foreach ($this->_memTypeSelected
as $memType) {
1148 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE,
1152 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
1153 CRM_Core_BAO_CustomField
::getFields('Membership',
1159 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1166 foreach ($this->_memTypeSelected
as $memType) {
1167 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1172 $membershipType = implode(', ', $membershipTypes);
1174 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1175 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($ids['userId']);
1177 //CRM-13981, allow different person as a soft-contributor of chosen type
1178 if ($this->_contributorContactID
!= $this->_contactID
) {
1179 $params['contribution_contact_id'] = $this->_contributorContactID
;
1180 if (!empty($this->_params
['soft_credit_type_id'])) {
1181 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1182 $softParams['contact_id'] = $this->_contactID
;
1185 if (!empty($formValues['record_contribution'])) {
1186 $recordContribution = array(
1188 'financial_type_id',
1189 'payment_instrument_id',
1191 'contribution_status_id',
1197 foreach ($recordContribution as $f) {
1198 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1201 if (!$this->_onlinePendingContributionId
) {
1202 if (empty($formValues['source'])) {
1203 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
1206 $params['contribution_source'] = $formValues['source'];
1210 if (empty($params['is_override']) &&
1211 CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1213 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1214 $params['status_id'] = array_search('Pending', $allStatus);
1215 $params['skipStatusCal'] = TRUE;
1216 $params['is_pay_later'] = 1;
1217 $this->assign('is_pay_later', 1);
1220 if (!empty($formValues['send_receipt'])) {
1221 $params['receipt_date'] = CRM_Utils_Array
::value('receive_date', $formValues);
1224 //insert financial type name in receipt.
1225 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1226 $formValues['financial_type_id']
1230 // process line items, until no previous line items.
1231 if (!empty($lineItem)) {
1232 $params['lineItems'] = $lineItem;
1233 $params['processPriceSet'] = TRUE;
1235 $createdMemberships = array();
1237 if (empty($formValues['total_amount']) && !$priceSetId) {
1238 // if total amount not provided minimum for membership type is used
1239 $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1240 $formValues['membership_type_id'][1], 'minimum_fee'
1244 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1247 if ($priceSetId && !$isQuickConfig) {
1248 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1254 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $formValues);
1257 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($formValues['payment_processor_id'],
1261 //get the payment processor id as per mode.
1262 $params['payment_processor_id'] = $this->_params
['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1265 $now = date('YmdHis');
1268 // set email for primary location.
1269 $fields['email-Primary'] = 1;
1270 $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail
;
1271 $params['register_date'] = $now;
1273 // now set the values for the billing location.
1274 foreach ($this->_fields
as $name => $dontCare) {
1278 // also add location name to the array
1279 $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array
::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array
::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array
::value('billing_last_name', $formValues);
1281 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1283 $fields["address_name-{$this->_bltID}"] = 1;
1284 //ensure we don't over-write the payer's email with the member's email
1285 if ($this->_contributorContactID
== $this->_contactID
) {
1286 $fields["email-{$this->_bltID}"] = 1;
1289 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type');
1291 $nameFields = array('first_name', 'middle_name', 'last_name');
1293 foreach ($nameFields as $name) {
1295 if (array_key_exists("billing_$name", $formValues)) {
1296 $formValues[$name] = $formValues["billing_{$name}"];
1297 $formValues['preserveDBName'] = TRUE;
1300 if ($this->_contributorContactID
== $this->_contactID
) {
1301 //see CRM-12869 for discussion of why we don't do this for separate payee payments
1302 CRM_Contact_BAO_Contact
::createProfileContact($formValues, $fields,
1303 $this->_contributorContactID
, NULL, NULL, $ctype
1307 // add all the additional payment params we need
1308 $this->_params
["state_province-{$this->_bltID}"] = $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
1309 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1311 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1312 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1313 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1314 $this->_params
['amount'] = $params['total_amount'];
1315 $this->_params
['currencyID'] = $config->defaultCurrency
;
1316 $this->_params
['description'] = ts('Office Credit Card Membership Signup Contribution');
1317 $this->_params
['payment_action'] = 'Sale';
1318 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1319 $this->_params
['financial_type_id'] = $params['financial_type_id'];
1321 // at this point we've created a contact and stored its address etc
1322 // all the payment processors expect the name and address to be in the
1323 // so we copy stuff over to first_name etc.
1324 $paymentParams = $this->_params
;
1325 $paymentParams['contactID'] = $this->_contributorContactID
;
1326 //CRM-10377 if payment is by an alternate contact then we need to set that person
1327 // as the contact in the payment params
1328 if ($this->_contributorContactID
!= $this->_contactID
) {
1329 if (!empty($this->_params
['soft_credit_type_id'])) {
1330 $softParams['contact_id'] = $params['contact_id'];
1331 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1334 if (!empty($this->_params
['send_receipt'])) {
1335 $paymentParams['email'] = $this->_contributorEmail
;
1338 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1340 // CRM-7137 -for recurring membership,
1341 // we do need contribution and recuring records.
1343 if (!empty($paymentParams['is_recur'])) {
1344 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1346 $contributionType = new CRM_Financial_DAO_FinancialType();
1347 $contributionType->id
= $params['financial_type_id'];
1348 if (!$contributionType->find(TRUE)) {
1349 CRM_Core_Error
::fatal('Could not find a system table');
1352 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1355 $this->_contributorContactID
,
1363 //create new soft-credit record, CRM-13981
1365 $softParams['contribution_id'] = $contribution->id
;
1366 $softParams['currency'] = $contribution->currency
;
1367 $softParams['amount'] = $contribution->total_amount
;
1368 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1371 $paymentParams['contactID'] = $this->_contactID
;
1372 $paymentParams['contributionID'] = $contribution->id
;
1373 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1374 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1375 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1376 $ids['contribution'] = $contribution->id
;
1377 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1378 $params['status_id'] = array_search('Pending', $allStatus);
1379 $params['skipStatusCal'] = TRUE;
1381 //as membership is pending set dates to null.
1382 $memberDates = array(
1383 'join_date' => 'joinDate',
1384 'start_date' => 'startDate',
1385 'end_date' => 'endDate',
1388 foreach ($memberDates as $dp => $dv) {
1390 foreach ($this->_memTypeSelected
as $memType) {
1391 $membershipTypeValues[$memType][$dv] = NULL;
1396 if ($params['total_amount'] > 0.0) {
1397 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this);
1398 $result = $payment->doDirectPayment($paymentParams);
1401 if (is_a($result, 'CRM_Core_Error')) {
1402 //make sure to cleanup db for recurring case.
1403 if (!empty($paymentParams['contributionID'])) {
1404 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1406 if (!empty($paymentParams['contributionRecurID'])) {
1407 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1410 CRM_Core_Error
::displaySessionError($result);
1411 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1412 "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
1417 $this->_params
= array_merge($this->_params
, $result);
1418 //assign amount to template if payment was successful
1419 $this->assign('amount', $params['total_amount']);
1422 $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ?
2 : 1;
1423 $params['receive_date'] = $now;
1424 $params['invoice_id'] = $this->_params
['invoiceID'];
1425 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1426 array(1 => $membershipType, 2 => $userName)
1428 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1429 $params['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1430 $params['payment_instrument_id'] = 1;
1431 $params['is_test'] = ($this->_mode
== 'live') ?
0 : 1;
1432 if (!empty($this->_params
['send_receipt'])) {
1433 $params['receipt_date'] = $now;
1436 $params['receipt_date'] = NULL;
1439 $this->set('params', $this->_params
);
1440 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1441 $this->assign('receive_date',
1442 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1445 // required for creating membership for related contacts
1446 $params['action'] = $this->_action
;
1448 //create membership record.
1450 foreach ($this->_memTypeSelected
as $memType) {
1452 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1454 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1457 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1459 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1460 $membershipParams['soft_credit'] = $softParams;
1462 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1463 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1464 unset($params['lineItems']);
1465 $this->_membershipIDs
[] = $membership->id
;
1466 $createdMemberships[$memType] = $membership;
1472 $params['action'] = $this->_action
;
1473 if ($this->_onlinePendingContributionId
&& !empty($formValues['record_contribution'])) {
1475 // update membership as well as contribution object, CRM-4395
1476 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1477 $params['componentId'] = $params['id'];
1478 $params['componentName'] = 'contribute';
1479 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1480 if (!empty($result) && !empty($params['contribution_id'])) {
1481 $lineItem = array();
1482 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
1483 $itemId = key($lineItems);
1484 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1486 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1487 $fieldType = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1489 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1490 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1491 $lineItems[$itemId]['id'] = $itemId;
1492 $lineItem[$priceSetId] = $lineItems;
1493 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1494 $contributionBAO->id
= $params['contribution_id'];
1495 $contributionBAO->contact_id
= $params['contact_id'];
1496 $contributionBAO->find();
1497 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1499 //create new soft-credit record, CRM-13981
1501 $softParams['contribution_id'] = $params['contribution_id'];
1502 while ($contributionBAO->fetch()) {
1503 $softParams['currency'] = $contributionBAO->currency
;
1504 $softParams['amount'] = $contributionBAO->total_amount
;
1506 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1510 //carry updated membership object.
1511 $membership = new CRM_Member_DAO_Membership();
1512 $membership->id
= $this->_id
;
1513 $membership->find(TRUE);
1516 if ($membership->end_date
) {
1517 //display end date w/ status message.
1518 $endDate = $membership->end_date
;
1520 if (!in_array($membership->status_id
, array(
1522 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1523 array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus()),
1529 // suppress form values in template.
1530 $this->assign('cancelled', $cancelled);
1532 // FIX ME: need to recheck this
1533 // here we might updated dates, so get from object.
1534 foreach ($calcDates[$membership->membership_type_id
] as $date => & $val) {
1535 if ($membership->$date) {
1536 $val = $membership->$date;
1540 $createdMemberships[] = $membership;
1544 foreach ($this->_memTypeSelected
as $memType) {
1545 if ($count && !empty($formValues['record_contribution']) &&
1546 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1548 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1551 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1552 if (!empty($formValues['int_amount'])) {
1553 $init_amount = array();
1554 foreach ($formValues as $key => $value) {
1555 if (strstr($key, 'txt-price')) {
1556 $init_amount[$key] = $value;
1559 $membershipParams['init_amount'] = $init_amount;
1562 if (!empty($softParams)) {
1563 $membershipParams['soft_credit'] = $softParams;
1566 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1567 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1568 unset($params['lineItems']);
1570 $this->_membershipIDs
[] = $membership->id
;
1571 $createdMemberships[$memType] = $membership;
1577 if (!empty($lineItem[$priceSetId])) {
1578 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,'contribution_invoice_settings');
1579 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1581 $totalTaxAmount = 0;
1582 foreach ($lineItem[$priceSetId] as & $priceFieldOp) {
1583 if (!empty($priceFieldOp['membership_type_id'])) {
1584 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date
::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
1585 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date
::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
1588 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1590 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1592 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1596 $dataArray = array();
1597 foreach ($lineItem[$priceSetId] as $key => $value) {
1598 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1599 if (isset($dataArray[$value['tax_rate']])) {
1600 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1602 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
1607 $this->assign('totalTaxAmount', $totalTaxAmount);
1608 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1610 $this->assign('dataArray', $dataArray);
1613 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1615 $receiptSend = FALSE;
1616 if (!empty($formValues['send_receipt'])) {
1617 $receiptSend = TRUE;
1619 $formValues['contact_id'] = $this->_contactID
;
1621 $formValues['contribution_id'] = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1622 // send email receipt
1623 $mailSend = self
::emailReceipt($this, $formValues, $membership);
1626 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1627 //end date can be modified by hooks, so if end date is set then use it.
1628 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1630 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName
));
1631 if ($endDate && $endDate !== 'null') {
1632 $endDate = CRM_Utils_Date
::customFormat($endDate);
1633 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
1636 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1639 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1640 // FIX ME: fix status messages
1642 $statusMsg = array();
1643 foreach ($membershipTypes as $memType => $membershipType) {
1644 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1645 1 => $membershipType,
1646 2 => $this->_memberDisplayName
1649 $membership = $createdMemberships[$memType];
1650 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1652 //get the end date from calculated dates.
1653 if (!$memEndDate && empty($params['is_recur'])) {
1654 $memEndDate = CRM_Utils_Array
::value('end_date', $calcDates[$memType]);
1657 if ($memEndDate && $memEndDate !== 'null') {
1658 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1659 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
1662 $statusMsg = implode('<br/>', $statusMsg);
1663 if ($receiptSend && $mailSend) {
1664 $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1668 // finally set membership id if already not set
1670 $this->_id
= $membership->id
;
1673 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1675 $buttonName = $this->controller
->getButtonName();
1676 if ($this->_context
== 'standalone') {
1677 if ($buttonName == $this->getButtonName('upload', 'new')) {
1678 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1679 'reset=1&action=add&context=standalone'
1683 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1684 "reset=1&cid={$this->_contactID}&selectedChild=member"
1688 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1689 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1690 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1696 * Send email receipt
1698 * @param CRM_Core_Form $form form object
1699 * @param array $formValues
1700 * @param object $membership object
1702 * @return boolean true if mail was sent successfully
1705 static function emailReceipt(&$form, &$formValues, &$membership) {
1706 // retrieve 'from email id' for acknowledgement
1707 $receiptFrom = $formValues['from_email_address'];
1709 if (!empty($formValues['payment_instrument_id'])) {
1710 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
1711 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1714 // retrieve custom data
1715 $customFields = $customValues = array();
1716 if (property_exists($form, '_groupTree')
1717 && !empty($form->_groupTree
)
1719 foreach ($form->_groupTree
as $groupID => $group) {
1720 if ($groupID == 'info') {
1723 foreach ($group['fields'] as $k => $field) {
1724 $field['title'] = $field['label'];
1725 $customFields["custom_{$k}"] = $field;
1730 $members = array(array('member_id', '=', $membership->id
, 0, 0));
1731 // check whether its a test drive
1732 if ($form->_mode
== 'test') {
1733 $members[] = array('member_test', '=', 1, 0, 0);
1736 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1739 if (!empty($form->_params
['billing_first_name'])) {
1740 $name = $form->_params
['billing_first_name'];
1743 if (!empty($form->_params
['billing_middle_name'])) {
1744 $name .= " {$form->_params['billing_middle_name']}";
1747 if (!empty($form->_params
['billing_last_name'])) {
1748 $name .= " {$form->_params['billing_last_name']}";
1751 $form->assign('billingName', $name);
1753 // assign the address formatted up for display
1754 $addressParts = array(
1755 "street_address-{$form->_bltID}",
1756 "city-{$form->_bltID}",
1757 "postal_code-{$form->_bltID}",
1758 "state_province-{$form->_bltID}",
1759 "country-{$form->_bltID}",
1761 $addressFields = array();
1762 foreach ($addressParts as $part) {
1763 list($n, $id) = explode('-', $part);
1764 if (isset($form->_params
['billing_' . $part])) {
1765 $addressFields[$n] = $form->_params
['billing_' . $part];
1768 $form->assign('address', CRM_Utils_Address
::format($addressFields));
1770 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
1771 $date = CRM_Utils_Date
::mysqlToIso($date);
1772 $form->assign('credit_card_exp_date', $date);
1773 $form->assign('credit_card_number',
1774 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
1776 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
1777 $form->assign('contributeMode', 'direct');
1778 $form->assign('isAmountzero', 0);
1779 $form->assign('is_pay_later', 0);
1780 $form->assign('isPrimary', 1);
1783 $form->assign('module', 'Membership');
1784 $form->assign('contactID', $formValues['contact_id']);
1786 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
1788 if (!empty($formValues['contribution_id'])) {
1789 $form->assign('contributionID', $formValues['contribution_id']);
1791 elseif (isset($form->_onlinePendingContributionId
)) {
1792 $form->assign('contributionID', $form->_onlinePendingContributionId
);
1795 if (!empty($formValues['contribution_status_id'])) {
1796 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1797 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
1800 if (!empty($formValues['is_renew'])) {
1801 $form->assign('receiptType', 'membership renewal');
1804 $form->assign('receiptType', 'membership signup');
1806 $form->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $formValues)));
1807 $form->assign('formValues', $formValues);
1809 if (empty($lineItem)) {
1810 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1811 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1812 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1815 $form->assign('customValues', $customValues);
1816 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1817 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1818 // in this case the form is being called statically from the batch editing screen
1819 // having one class in the form layer call another statically is not greate
1820 // & we should aim to move this function to the BAO layer in future.
1821 // however, we can assume that the contact_id passed in by the batch
1822 // function will be the recipient
1824 $form->_contributorDisplayName
,
1825 $form->_contributorEmail
1826 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails(
1827 $formValues['contact_id']
1829 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1830 $form->_receiptContactId
= $formValues['contact_id'];
1833 $template = CRM_Core_Smarty
::singleton( );
1834 $taxAmt = $template->get_template_vars('dataArray');
1835 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1836 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1837 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1838 if ((!empty($taxAmt) ||
isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1842 $isEmailPdf = False;
1845 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1847 'groupName' => 'msg_tpl_workflow_membership',
1848 'valueName' => 'membership_offline_receipt',
1849 'contactId' => $form->_receiptContactId
,
1850 'from' => $receiptFrom,
1851 'toName' => $form->_contributorDisplayName
,
1852 'toEmail' => $form->_contributorEmail
,
1853 'PDFFilename' => ts('receipt').'.pdf',
1854 'isEmailPdf' => $isEmailPdf,
1855 'contributionId' => $formValues['contribution_id'],
1856 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
)