3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
216 public function setDefaultValues() {
217 if ($this->_cdType
) {
218 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
221 if ($this->_priceSetId
) {
222 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
225 $defaults = parent
::setDefaultValues();
227 //setting default join date and receive date
228 list($now, $currentTime) = CRM_Utils_Date
::setDateDefaults();
229 if ($this->_action
== CRM_Core_Action
::ADD
) {
230 $defaults['receive_date'] = $now;
231 $defaults['receive_date_time'] = $currentTime;
234 if (is_numeric($this->_memType
)) {
235 $defaults['membership_type_id'] = array();
236 $defaults['membership_type_id'][0] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
238 'member_of_contact_id',
241 $defaults['membership_type_id'][1] = $this->_memType
;
244 $defaults['membership_type_id'] = $this->_memType
;
247 $defaults['num_terms'] = 1;
249 if (!empty($defaults['id'])) {
250 if ($this->_onlinePendingContributionId
) {
251 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
254 $contributionId = CRM_Core_DAO
::singleValueQuery("
255 SELECT contribution_id
256 FROM civicrm_membership_payment
257 WHERE membership_id = $this->_id
258 ORDER BY contribution_id
261 if ($contributionId) {
262 $defaults['record_contribution'] = $contributionId;
267 //set Soft Credit Type to Gift by default
268 $scTypes = CRM_Core_OptionGroup
::values("soft_credit_type");
269 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
271 if (!empty($defaults['record_contribution']) && !$this->_mode
) {
272 $contributionParams = array('id' => $defaults['record_contribution']);
273 $contributionIds = array();
275 //keep main object campaign in hand.
276 $memberCampaignId = CRM_Utils_Array
::value('campaign_id', $defaults);
278 CRM_Contribute_BAO_Contribution
::getValues($contributionParams, $defaults, $contributionIds);
280 //get back original object campaign id.
281 $defaults['campaign_id'] = $memberCampaignId;
283 if (!empty($defaults['receive_date'])) {
284 list($defaults['receive_date']) = CRM_Utils_Date
::setDateDefaults($defaults['receive_date']);
287 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
288 if (!empty($defaults['membership_source'])) {
289 $defaults['source'] = $defaults['membership_source'];
293 if (empty($defaults['payment_instrument_id'])) {
294 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
297 // User must explicitly choose to send a receipt in both add and update mode.
298 $defaults['send_receipt'] = 0;
300 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
301 // in this mode by default uncheck this checkbox
302 unset($defaults['record_contribution']);
305 if (!empty($defaults['id'])) {
306 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
309 $alreadyAutoRenew = FALSE;
310 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
311 $defaults['auto_renew'] = 1;
312 $alreadyAutoRenew = TRUE;
314 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
316 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
318 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
320 if (!empty($defaults['is_pay_later'])) {
321 $this->assign('is_pay_later', TRUE);
324 // set default country from config if no country set
325 $config = CRM_Core_Config
::singleton();
326 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
327 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
330 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
331 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
334 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
335 $defaults = array_merge($defaults, $billingDefaults);
337 // // hack to simplify credit card entry for testing
338 // $defaults['credit_card_type'] = 'Visa';
339 // $defaults['credit_card_number'] = '4807731747657838';
340 // $defaults['cvv2'] = '000';
341 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
344 $dates = array('join_date', 'start_date', 'end_date');
345 foreach ($dates as $key) {
346 if (!empty($defaults[$key])) {
347 list($defaults[$key]) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults));
351 //setting default join date if there is no join date
352 if (empty($defaults['join_date'])) {
353 $defaults['join_date'] = $now;
356 if (!empty($defaults['membership_end_date'])) {
357 $this->assign('endDate', $defaults['membership_end_date']);
364 * Build the form object
368 public function buildQuickForm() {
369 if ($this->_cdType
) {
370 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
373 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
374 $config = CRM_Core_Config
::singleton();
375 $this->assign('currency', $config->defaultCurrencySymbol
);
376 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,'contribution_invoice_settings');
377 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
378 if (isset($invoicing)){
379 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
381 // build price set form.
382 $buildPriceSet = FALSE;
383 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
384 if (!empty($_POST['price_set_id'])) {
385 $buildPriceSet = TRUE;
387 $getOnlyPriceSetElements = TRUE;
388 if (!$this->_priceSetId
) {
389 $this->_priceSetId
= $_POST['price_set_id'];
390 $getOnlyPriceSetElements = FALSE;
393 $this->set('priceSetId', $this->_priceSetId
);
394 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
396 $optionsMembershipTypes = array();
397 foreach ($this->_priceSet
['fields'] as $pField) {
398 if (empty($pField['options'])) {
401 foreach ($pField['options'] as $opId => $opValues) {
402 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
406 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
408 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
409 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
411 // get only price set form elements.
412 if ($getOnlyPriceSetElements) {
417 // use to build form during form rule.
418 $this->assign('buildPriceSet', $buildPriceSet);
420 if ($this->_action
& CRM_Core_Action
::ADD
) {
421 $buildPriceSet = FALSE;
422 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
423 if (!empty($priceSets)) {
424 $buildPriceSet = TRUE;
427 if ($buildPriceSet) {
428 $this->add('select', 'price_set_id', ts('Choose price set'),
430 '' => ts('Choose price set')
432 NULL, array('onchange' => "buildAmount( this.value );")
435 $this->assign('hasPriceSets', $buildPriceSet);
438 //need to assign custom data type and subtype to the template
439 $this->assign('customDataType', 'Membership');
440 $this->assign('customDataSubType', $this->_memType
);
441 $this->assign('entityID', $this->_id
);
443 if ($this->_action
& CRM_Core_Action
::DELETE
) {
444 $this->addButtons(array(
447 'name' => ts('Delete'),
448 'spacing' => ' ',
453 'name' => ts('Cancel'),
460 if ($this->_context
== 'standalone') {
461 $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
464 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
466 $dao = new CRM_Member_DAO_MembershipType();
467 $dao->domain_id
= CRM_Core_Config
::domainID();
470 // retrieve all memberships
471 $allMemberships = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this);
473 $allMembershipInfo = $membershipType = array();
474 foreach ($allMemberships as $key => $values) {
475 if (!empty($values['is_active'])) {
476 $membershipType[$key] = CRM_Utils_Array
::value('name', $values);
477 if ($this->_mode
&& empty($values['minimum_fee'])) {
481 $memberOfContactId = CRM_Utils_Array
::value('member_of_contact_id', $values);
482 if (empty($selMemTypeOrg[$memberOfContactId])) {
483 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
489 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
491 if (empty($selOrgMemType[$memberOfContactId][$key])) {
492 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array
::value('name', $values);
496 // build membership info array, which is used when membership type is selected to:
497 // - set the payment information block
498 // - set the max related block
499 $allMembershipInfo[$key] = array(
500 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $values),
501 'total_amount' => CRM_Utils_Money
::format($values['minimum_fee'], NULL, '%a'),
502 'total_amount_numeric' => CRM_Utils_Array
::value('minimum_fee', $values),
503 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $values),
504 'has_related' => isset($values['relationship_type_id']),
505 'max_related' => CRM_Utils_Array
::value('max_related', $values),
510 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
512 // show organization by default, if only one organization in
514 if (count($selMemTypeOrg) == 2) {
515 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
517 //sort membership organization and type, CRM-6099
518 natcasesort($selMemTypeOrg);
519 foreach ($selOrgMemType as $index => $orgMembershipType) {
520 natcasesort($orgMembershipType);
521 $selOrgMemType[$index] = $orgMembershipType;
524 $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
526 //build the form for auto renew.
527 $recurProcessor = $autoRenew = array();
528 if ($this->_mode ||
($this->_action
& CRM_Core_Action
::UPDATE
)) {
529 $autoRenewElement = $this->addElement('checkbox',
531 ts('Membership renewed automatically'),
533 array('onclick' => "buildReceiptANDNotice( );")
537 //get the valid recurring processors.
538 $recurring = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
539 $recurProcessor = array_intersect_assoc($this->_processors
, $recurring);
540 $autoRenew = array();
541 if (!empty($recurProcessor)) {
542 if (!empty($membershipType)) {
548 FROM civicrm_membership_type
549 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
550 $recurMembershipTypes = CRM_Core_DAO
::executeQuery($sql);
551 while ($recurMembershipTypes->fetch()) {
552 $autoRenew[$recurMembershipTypes->id
] = $recurMembershipTypes->auto_renew
;
559 $this->_recurMembershipTypes
[$recurMembershipTypes->id
][$fld] = $recurMembershipTypes->$fld;
565 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
570 $allowAutoRenew = FALSE;
571 if ($this->_mode
&& !empty($recurProcessor)) {
572 $allowAutoRenew = TRUE;
574 $this->assign('allowAutoRenew', $allowAutoRenew);
575 $this->assign('autoRenewOptions', json_encode($autoRenew));
576 $this->assign('recurProcessor', json_encode($recurProcessor));
578 // for max_related: a little JS to show/hide & set default value
579 $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
580 $this->add('text', 'max_related', ts('Max related'),
581 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
584 $sel = & $this->addElement('hierselect',
585 'membership_type_id',
586 ts('Membership Organization and Type'),
590 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
596 $this->applyFilter('__ALL__', 'trim');
598 if ($this->_action
& CRM_Core_Action
::ADD
) {
599 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
602 $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
603 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
604 $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
606 $elements[] = $endDate;
609 $this->add('text', 'source', ts('Source'),
610 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
613 //CRM-7362 --add campaigns.
616 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
618 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
621 $this->add('select', 'status_id', ts('Membership Status'),
622 array('' => ts('- select -')) + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
624 $statusOverride = $this->addElement('checkbox', 'is_override',
625 ts('Status Override?'), NULL,
626 array('onClick' => 'showHideMemberStatus()')
628 if ($statusOverride) {
629 $elements[] = $statusOverride;
632 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
634 $this->add('text', 'total_amount', ts('Amount'));
635 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
637 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
639 $this->add('select', 'payment_instrument_id',
641 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
642 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
644 $this->add('text', 'trxn_id', ts('Transaction ID'));
645 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
646 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id
, 'trxn_id')
649 $allowStatuses = array();
650 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
651 if ($this->_onlinePendingContributionId
) {
652 $statusNames = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
653 foreach ($statusNames as $val => $name) {
654 if (in_array($name, array(
661 $allowStatuses[$val] = $statuses[$val];
665 $allowStatuses = $statuses;
667 $this->add('select', 'contribution_status_id',
668 ts('Payment Status'), $allowStatuses
670 $this->add('text', 'check_number', ts('Check Number'),
671 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
675 //add field for amount to allow an amount to be entered that differs from minimum
676 $this->add('text', 'total_amount', ts('Amount'));
678 $this->add('select', 'financial_type_id',
679 ts('Financial Type'),
680 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType()
683 //CRM-10223 - allow contribution to be recorded against different contact
684 // causes a conflict in standalone mode so skip in standalone for now
685 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
686 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
687 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
690 $this->addElement('checkbox',
692 ts('Send Confirmation and Receipt?'), NULL,
693 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);")
696 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
698 $this->add('textarea', 'receipt_text_signup', ts('Receipt Message'));
700 // Retrieve the name and email of the contact - this will be the TO for receipt email
701 if ($this->_contactID
) {
702 list($this->_memberDisplayName
,
704 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
706 $this->assign('emailExists', $this->_memberEmail
);
707 $this->assign('displayName', $this->_memberDisplayName
);
711 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
712 $recurContributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
,
713 'contribution_recur_id'
715 if ($recurContributionId && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
)) {
717 if (CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
718 $this->assign('cancelAutoRenew',
719 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
722 foreach ($elements as $elem) {
727 $this->assign('isRecur', $isRecur);
729 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
731 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
734 $this->assign('outBound_option', $mailingInfo['outBound_option']);
736 parent
::buildQuickForm();
742 * @param array $params (ref.) an assoc array of name/value pairs
747 * @throws CiviCRM_API3_Exception
748 * @return mixed true or array of errors
751 public static function formRule($params, $files, $self) {
754 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
757 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
759 $priceFieldIDS = array();
760 foreach ($self->_priceSet
['fields'] as $priceIds => $dontCare) {
762 if (!empty($params['price_' . $priceIds])) {
763 if (is_array($params['price_' . $priceIds])) {
764 foreach ($params['price_' . $priceIds] as $priceFldVal => $isSet) {
766 $priceFieldIDS[] = $priceFldVal;
771 $priceFieldIDS[] = $params['price_' . $priceIds];
776 if (!empty($priceFieldIDS)) {
777 $ids = implode(',', $priceFieldIDS);
779 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
780 foreach ($count as $id => $occurance) {
781 if ($occurance > 1) {
782 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
786 foreach ($priceFieldIDS as $priceFieldId) {
787 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
788 $self->_memTypeSelected
[$id] = $id;
793 elseif (empty($params['membership_type_id'][1])) {
794 $errors['membership_type_id'] = ts('Please select a membership type.');
797 $self->_memTypeSelected
[] = $params['membership_type_id'][1];
801 $numterms = CRM_Utils_Array
::value('num_terms', $params);
802 if ($numterms && intval($numterms) != $numterms) {
803 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
807 // Return error if empty $self->_memTypeSelected
808 if ($priceSetId && empty($errors) && empty($self->_memTypeSelected
)) {
809 $errors['_qf_default'] = ts('Select at least one membership option.');
812 if (!empty($errors) && (count($self->_memTypeSelected
) > 1)) {
813 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($self->_memTypeSelected
);
814 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
815 foreach ($duplicateMemberOfContacts as $countDuplicate) {
816 if ($countDuplicate > 1) {
817 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
822 if (!empty($errors)) {
826 if ($priceSetId && !$self->_mode
&& empty($params['record_contribution'])) {
827 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
830 if (!$priceSetId && $self->_mode
&& empty($params['financial_type_id'])) {
831 $errors['financial_type_id'] = ts('Please enter the financial Type.');
834 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
835 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
838 if (!empty($params['is_different_contribution_contact'])) {
839 if (empty($params['soft_credit_type_id'])) {
840 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
842 if (empty($params['soft_credit_contact_id'])) {
843 $errors['soft_credit_contact_id'] = ts('Please select a contact');
847 if (!empty($params['payment_processor_id'])) {
848 // make sure that credit card number and cvv are valid
849 CRM_Core_Payment_Form
::validateCreditCard($params, $errors);
853 if (!empty($params['join_date'])) {
855 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
857 foreach ($self->_memTypeSelected
as $memType) {
859 if (!empty($params['start_date'])) {
860 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
863 // if end date is set, ensure that start date is also set
864 // and that end date is later than start date
866 if (!empty($params['end_date'])) {
867 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
870 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
872 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) == 'rolling') {
873 if ($startDate < $joinDate) {
874 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
879 if ($membershipDetails['duration_unit'] == 'lifetime') {
880 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
881 // process to update status based on end-date. The user must change the status now.
882 $result = civicrm_api3('MembershipStatus', 'get', array(
884 'is_current_member' => 0,
886 $tmp_statuses = $result['values'];
887 $status_ids = array();
888 foreach($tmp_statuses as $cur_stat) {
889 $status_ids[] = $cur_stat['id'];
891 if (empty($params['status_id']) ||
in_array( $params['status_id'] , $status_ids) == false) {
892 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
893 $errors['is_override'] = ts('This must be checked because you set an End Date for a lifetime membership');
898 $errors['start_date'] = ts('Start date must be set if end date is set.');
900 if ($endDate < $startDate) {
901 $errors['end_date'] = ts('End date must be the same or later than start date.');
906 // Default values for start and end dates if not supplied
908 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
915 $startDate = CRM_Utils_Array
::value('start_date',
920 $endDate = CRM_Utils_Array
::value('end_date',
925 //CRM-3724, check for availability of valid membership status.
926 if (empty($params['is_override']) && !isset($errors['_qf_default'])) {
927 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
935 if (empty($calcStatus)) {
936 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
937 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
938 $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));
940 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
942 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
948 $errors['join_date'] = ts('Please enter the Member Since.');
951 if (isset($params['is_override']) &&
952 $params['is_override'] && empty($params['status_id'])) {
953 $errors['status_id'] = ts('Please enter the status.');
956 //total amount condition arise when membership type having no
958 if (isset($params['record_contribution'])) {
959 if (!$params['financial_type_id']) {
960 $errors['financial_type_id'] = ts('Please enter the financial Type.');
962 if (CRM_Utils_System
::isNull($params['total_amount'])) {
963 $errors['total_amount'] = ts('Please enter the contribution.');
967 // validate contribution status for 'Failed'.
968 if ($self->_onlinePendingContributionId
&& !empty($params['record_contribution']) &&
969 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
970 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
973 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
976 return empty($errors) ?
TRUE : $errors;
980 * Process the form submission
985 public function postProcess() {
986 if ($this->_action
& CRM_Core_Action
::DELETE
) {
987 CRM_Member_BAO_Membership
::del($this->_id
);
991 $isTest = ($this->_mode
== 'test') ?
1 : 0;
994 if (!empty($this->_lineItem
)) {
995 $lineItems = $this->_lineItem
;
998 $config = CRM_Core_Config
::singleton();
999 // get the submitted form values.
1000 $this->_params
= $formValues = $this->controller
->exportValues($this->_name
);
1001 $this->convertDateFieldsToMySQL($formValues);
1003 $params = $softParams = $ids = array();
1005 $membershipTypeValues = array();
1006 foreach ($this->_memTypeSelected
as $memType) {
1007 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1010 //take the required membership recur values.
1011 if ($this->_mode
&& !empty($this->_params
['auto_renew'])) {
1012 $params['is_recur'] = $this->_params
['is_recur'] = $formValues['is_recur'] = TRUE;
1014 'frequency_interval' => 'duration_interval',
1015 'frequency_unit' => 'duration_unit',
1019 foreach ($this->_memTypeSelected
as $memType) {
1020 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1021 $this->_recurMembershipTypes
, array()
1023 foreach ($mapping as $mapVal => $mapParam) {
1024 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array
::value($mapParam,
1025 $recurMembershipTypeValues
1028 $this->_params
[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1029 $recurMembershipTypeValues
1036 // unset send-receipt option, since receipt will be sent when ipn is received.
1037 unset($this->_params
['send_receipt'], $formValues['send_receipt']);
1040 // process price set and get total amount and line items.
1041 $lineItem = array();
1043 if (!$priceSetId = CRM_Utils_Array
::value('price_set_id', $formValues)) {
1044 CRM_Member_BAO_Membership
::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
1047 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1051 $termsByType = array();
1053 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1054 $this->_params
, $lineItem[$priceSetId]);
1055 if (CRM_Utils_Array
::value('tax_amount', $this->_params
)) {
1056 $params['tax_amount'] = $this->_params
['tax_amount'];
1058 $params['total_amount'] = CRM_Utils_Array
::value('amount', $this->_params
);
1059 $submittedFinancialType = CRM_Utils_Array
::value('financial_type_id', $formValues);
1060 if (!empty($lineItem[$priceSetId])) {
1061 foreach ($lineItem[$priceSetId] as &$li) {
1062 if (!empty($li['membership_type_id'])) {
1063 if (!empty($li['membership_num_terms'])) {
1064 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1068 ///CRM-11529 for quick config backoffice transactions
1069 //when financial_type_id is passed in form, update the
1070 //lineitems with the financial type selected in form
1071 if ($isQuickConfig && $submittedFinancialType) {
1072 $li['financial_type_id'] = $submittedFinancialType;
1078 $this->storeContactFields($formValues);
1080 $params['contact_id'] = $this->_contactID
;
1089 foreach ($fields as $f) {
1090 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1094 // when is_override false ignore is_admin statuses during membership
1095 // status calculation. similarly we did fix for import in CRM-3570.
1096 if (empty($params['is_override'])) {
1097 $params['exclude_is_admin'] = TRUE;
1100 // process date params to mysql date format.
1102 'join_date' => 'joinDate',
1103 'start_date' => 'startDate',
1104 'end_date' => 'endDate',
1106 foreach ($dateTypes as $dateField => $dateVariable) {
1107 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1110 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1112 $calcDates = array();
1113 foreach ($this->_memTypeSelected
as $memType) {
1114 if (empty($memTypeNumTerms)) {
1115 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1117 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1118 $joinDate, $startDate, $endDate, $memTypeNumTerms
1122 foreach ($calcDates as $memType => $calcDate) {
1123 foreach (array_keys($dateTypes) as $d) {
1124 //first give priority to form values then calDates.
1125 $date = CRM_Utils_Array
::value($d, $formValues);
1127 $date = CRM_Utils_Array
::value($d, $calcDate);
1130 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1131 //$params[$d] = CRM_Utils_Date::processDate( $date );
1135 // max related memberships - take from form or inherit from membership type
1136 foreach ($this->_memTypeSelected
as $memType) {
1137 if (array_key_exists('max_related', $formValues)) {
1138 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array
::value('max_related', $formValues);
1143 $ids['membership'] = $params['id'] = $this->_id
;
1146 $session = CRM_Core_Session
::singleton();
1147 $ids['userId'] = $session->get('userID');
1149 // membership type custom data
1150 foreach ($this->_memTypeSelected
as $memType) {
1151 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE,
1155 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
1156 CRM_Core_BAO_CustomField
::getFields('Membership',
1162 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1169 foreach ($this->_memTypeSelected
as $memType) {
1170 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1175 $membershipType = implode(', ', $membershipTypes);
1177 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1178 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($ids['userId']);
1180 //CRM-13981, allow different person as a soft-contributor of chosen type
1181 if ($this->_contributorContactID
!= $this->_contactID
) {
1182 $params['contribution_contact_id'] = $this->_contributorContactID
;
1183 if (!empty($this->_params
['soft_credit_type_id'])) {
1184 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1185 $softParams['contact_id'] = $this->_contactID
;
1188 if (!empty($formValues['record_contribution'])) {
1189 $recordContribution = array(
1191 'financial_type_id',
1192 'payment_instrument_id',
1194 'contribution_status_id',
1200 foreach ($recordContribution as $f) {
1201 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1204 if (!$this->_onlinePendingContributionId
) {
1205 if (empty($formValues['source'])) {
1206 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
1209 $params['contribution_source'] = $formValues['source'];
1213 if (empty($params['is_override']) &&
1214 CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1216 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1217 $params['status_id'] = array_search('Pending', $allStatus);
1218 $params['skipStatusCal'] = TRUE;
1219 $params['is_pay_later'] = 1;
1220 $this->assign('is_pay_later', 1);
1223 if (!empty($formValues['send_receipt'])) {
1224 $params['receipt_date'] = CRM_Utils_Array
::value('receive_date', $formValues);
1227 //insert financial type name in receipt.
1228 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1229 $formValues['financial_type_id']
1233 // process line items, until no previous line items.
1234 if (!empty($lineItem)) {
1235 $params['lineItems'] = $lineItem;
1236 $params['processPriceSet'] = TRUE;
1238 $createdMemberships = array();
1240 if (empty($formValues['total_amount']) && !$priceSetId) {
1241 // if total amount not provided minimum for membership type is used
1242 $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1243 $formValues['membership_type_id'][1], 'minimum_fee'
1247 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1250 if ($priceSetId && !$isQuickConfig) {
1251 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1257 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $formValues);
1260 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($formValues['payment_processor_id'],
1264 //get the payment processor id as per mode.
1265 $params['payment_processor_id'] = $this->_params
['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1268 $now = date('YmdHis');
1271 // set email for primary location.
1272 $fields['email-Primary'] = 1;
1273 $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail
;
1274 $params['register_date'] = $now;
1276 // now set the values for the billing location.
1277 foreach ($this->_fields
as $name => $dontCare) {
1281 // also add location name to the array
1282 $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);
1284 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1286 $fields["address_name-{$this->_bltID}"] = 1;
1287 //ensure we don't over-write the payer's email with the member's email
1288 if ($this->_contributorContactID
== $this->_contactID
) {
1289 $fields["email-{$this->_bltID}"] = 1;
1292 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type');
1294 $nameFields = array('first_name', 'middle_name', 'last_name');
1296 foreach ($nameFields as $name) {
1298 if (array_key_exists("billing_$name", $formValues)) {
1299 $formValues[$name] = $formValues["billing_{$name}"];
1300 $formValues['preserveDBName'] = TRUE;
1303 if ($this->_contributorContactID
== $this->_contactID
) {
1304 //see CRM-12869 for discussion of why we don't do this for separate payee payments
1305 CRM_Contact_BAO_Contact
::createProfileContact($formValues, $fields,
1306 $this->_contributorContactID
, NULL, NULL, $ctype
1310 // add all the additional payment params we need
1311 $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}"]);
1312 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1314 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1315 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1316 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1317 $this->_params
['amount'] = $params['total_amount'];
1318 $this->_params
['currencyID'] = $config->defaultCurrency
;
1319 $this->_params
['description'] = ts('Office Credit Card Membership Signup Contribution');
1320 $this->_params
['payment_action'] = 'Sale';
1321 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1322 $this->_params
['financial_type_id'] = $params['financial_type_id'];
1324 // at this point we've created a contact and stored its address etc
1325 // all the payment processors expect the name and address to be in the
1326 // so we copy stuff over to first_name etc.
1327 $paymentParams = $this->_params
;
1328 $paymentParams['contactID'] = $this->_contributorContactID
;
1329 //CRM-10377 if payment is by an alternate contact then we need to set that person
1330 // as the contact in the payment params
1331 if ($this->_contributorContactID
!= $this->_contactID
) {
1332 if (!empty($this->_params
['soft_credit_type_id'])) {
1333 $softParams['contact_id'] = $params['contact_id'];
1334 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1337 if (!empty($this->_params
['send_receipt'])) {
1338 $paymentParams['email'] = $this->_contributorEmail
;
1341 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1343 // CRM-7137 -for recurring membership,
1344 // we do need contribution and recuring records.
1346 if (!empty($paymentParams['is_recur'])) {
1347 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1349 $contributionType = new CRM_Financial_DAO_FinancialType();
1350 $contributionType->id
= $params['financial_type_id'];
1351 if (!$contributionType->find(TRUE)) {
1352 CRM_Core_Error
::fatal('Could not find a system table');
1355 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1358 $this->_contributorContactID
,
1366 //create new soft-credit record, CRM-13981
1368 $softParams['contribution_id'] = $contribution->id
;
1369 $softParams['currency'] = $contribution->currency
;
1370 $softParams['amount'] = $contribution->total_amount
;
1371 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1374 $paymentParams['contactID'] = $this->_contactID
;
1375 $paymentParams['contributionID'] = $contribution->id
;
1376 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1377 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1378 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1379 $ids['contribution'] = $contribution->id
;
1380 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1381 $params['status_id'] = array_search('Pending', $allStatus);
1382 $params['skipStatusCal'] = TRUE;
1384 //as membership is pending set dates to null.
1385 $memberDates = array(
1386 'join_date' => 'joinDate',
1387 'start_date' => 'startDate',
1388 'end_date' => 'endDate',
1391 foreach ($memberDates as $dp => $dv) {
1393 foreach ($this->_memTypeSelected
as $memType) {
1394 $membershipTypeValues[$memType][$dv] = NULL;
1399 if ($params['total_amount'] > 0.0) {
1400 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this);
1401 $result = $payment->doDirectPayment($paymentParams);
1404 if (is_a($result, 'CRM_Core_Error')) {
1405 //make sure to cleanup db for recurring case.
1406 if (!empty($paymentParams['contributionID'])) {
1407 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1409 if (!empty($paymentParams['contributionRecurID'])) {
1410 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1413 CRM_Core_Error
::displaySessionError($result);
1414 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1415 "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
1420 $this->_params
= array_merge($this->_params
, $result);
1421 //assign amount to template if payment was successful
1422 $this->assign('amount', $params['total_amount']);
1425 $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ?
2 : 1;
1426 $params['receive_date'] = $now;
1427 $params['invoice_id'] = $this->_params
['invoiceID'];
1428 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1429 array(1 => $membershipType, 2 => $userName)
1431 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1432 $params['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1433 $params['payment_instrument_id'] = 1;
1434 $params['is_test'] = ($this->_mode
== 'live') ?
0 : 1;
1435 if (!empty($this->_params
['send_receipt'])) {
1436 $params['receipt_date'] = $now;
1439 $params['receipt_date'] = NULL;
1442 $this->set('params', $this->_params
);
1443 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1444 $this->assign('receive_date',
1445 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1448 // required for creating membership for related contacts
1449 $params['action'] = $this->_action
;
1451 //create membership record.
1453 foreach ($this->_memTypeSelected
as $memType) {
1455 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1457 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1460 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1462 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1463 $membershipParams['soft_credit'] = $softParams;
1465 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1466 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1467 unset($params['lineItems']);
1468 $this->_membershipIDs
[] = $membership->id
;
1469 $createdMemberships[$memType] = $membership;
1475 $params['action'] = $this->_action
;
1476 if ($this->_onlinePendingContributionId
&& !empty($formValues['record_contribution'])) {
1478 // update membership as well as contribution object, CRM-4395
1479 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1480 $params['componentId'] = $params['id'];
1481 $params['componentName'] = 'contribute';
1482 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1483 if (!empty($result) && !empty($params['contribution_id'])) {
1484 $lineItem = array();
1485 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
1486 $itemId = key($lineItems);
1487 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1489 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1490 $fieldType = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1492 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1493 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1494 $lineItems[$itemId]['id'] = $itemId;
1495 $lineItem[$priceSetId] = $lineItems;
1496 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1497 $contributionBAO->id
= $params['contribution_id'];
1498 $contributionBAO->contact_id
= $params['contact_id'];
1499 $contributionBAO->find();
1500 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1502 //create new soft-credit record, CRM-13981
1504 $softParams['contribution_id'] = $params['contribution_id'];
1505 while ($contributionBAO->fetch()) {
1506 $softParams['currency'] = $contributionBAO->currency
;
1507 $softParams['amount'] = $contributionBAO->total_amount
;
1509 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1513 //carry updated membership object.
1514 $membership = new CRM_Member_DAO_Membership();
1515 $membership->id
= $this->_id
;
1516 $membership->find(TRUE);
1519 if ($membership->end_date
) {
1520 //display end date w/ status message.
1521 $endDate = $membership->end_date
;
1523 if (!in_array($membership->status_id
, array(
1525 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1526 array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus()),
1532 // suppress form values in template.
1533 $this->assign('cancelled', $cancelled);
1535 // FIX ME: need to recheck this
1536 // here we might updated dates, so get from object.
1537 foreach ($calcDates[$membership->membership_type_id
] as $date => & $val) {
1538 if ($membership->$date) {
1539 $val = $membership->$date;
1543 $createdMemberships[] = $membership;
1547 foreach ($this->_memTypeSelected
as $memType) {
1548 if ($count && !empty($formValues['record_contribution']) &&
1549 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1551 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1554 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1555 if (!empty($formValues['int_amount'])) {
1556 $init_amount = array();
1557 foreach ($formValues as $key => $value) {
1558 if (strstr($key, 'txt-price')) {
1559 $init_amount[$key] = $value;
1562 $membershipParams['init_amount'] = $init_amount;
1565 if (!empty($softParams)) {
1566 $membershipParams['soft_credit'] = $softParams;
1569 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1570 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1571 unset($params['lineItems']);
1573 $this->_membershipIDs
[] = $membership->id
;
1574 $createdMemberships[$memType] = $membership;
1580 if (!empty($lineItem[$priceSetId])) {
1581 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
,'contribution_invoice_settings');
1582 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1584 $totalTaxAmount = 0;
1585 foreach ($lineItem[$priceSetId] as & $priceFieldOp) {
1586 if (!empty($priceFieldOp['membership_type_id'])) {
1587 $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') : '-';
1588 $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') : '-';
1591 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1593 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1595 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1599 $dataArray = array();
1600 foreach ($lineItem[$priceSetId] as $key => $value) {
1601 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1602 if (isset($dataArray[$value['tax_rate']])) {
1603 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1605 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
1610 $this->assign('totalTaxAmount', $totalTaxAmount);
1611 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1613 $this->assign('dataArray', $dataArray);
1616 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1618 $receiptSend = FALSE;
1619 if (!empty($formValues['send_receipt'])) {
1620 $receiptSend = TRUE;
1622 $formValues['contact_id'] = $this->_contactID
;
1624 $formValues['contribution_id'] = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1625 // send email receipt
1626 $mailSend = self
::emailReceipt($this, $formValues, $membership);
1629 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1630 //end date can be modified by hooks, so if end date is set then use it.
1631 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1633 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName
));
1634 if ($endDate && $endDate !== 'null') {
1635 $endDate = CRM_Utils_Date
::customFormat($endDate);
1636 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
1639 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1642 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1643 // FIX ME: fix status messages
1645 $statusMsg = array();
1646 foreach ($membershipTypes as $memType => $membershipType) {
1647 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1648 1 => $membershipType,
1649 2 => $this->_memberDisplayName
1652 $membership = $createdMemberships[$memType];
1653 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1655 //get the end date from calculated dates.
1656 if (!$memEndDate && empty($params['is_recur'])) {
1657 $memEndDate = CRM_Utils_Array
::value('end_date', $calcDates[$memType]);
1660 if ($memEndDate && $memEndDate !== 'null') {
1661 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1662 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
1665 $statusMsg = implode('<br/>', $statusMsg);
1666 if ($receiptSend && $mailSend) {
1667 $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1671 // finally set membership id if already not set
1673 $this->_id
= $membership->id
;
1676 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1678 $buttonName = $this->controller
->getButtonName();
1679 if ($this->_context
== 'standalone') {
1680 if ($buttonName == $this->getButtonName('upload', 'new')) {
1681 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1682 'reset=1&action=add&context=standalone'
1686 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1687 "reset=1&cid={$this->_contactID}&selectedChild=member"
1691 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1692 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1693 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1699 * Send email receipt
1701 * @param CRM_Core_Form $form form object
1702 * @param array $formValues
1703 * @param object $membership object
1705 * @return boolean true if mail was sent successfully
1708 public static function emailReceipt(&$form, &$formValues, &$membership) {
1709 // retrieve 'from email id' for acknowledgement
1710 $receiptFrom = $formValues['from_email_address'];
1712 if (!empty($formValues['payment_instrument_id'])) {
1713 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
1714 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1717 // retrieve custom data
1718 $customFields = $customValues = array();
1719 if (property_exists($form, '_groupTree')
1720 && !empty($form->_groupTree
)
1722 foreach ($form->_groupTree
as $groupID => $group) {
1723 if ($groupID == 'info') {
1726 foreach ($group['fields'] as $k => $field) {
1727 $field['title'] = $field['label'];
1728 $customFields["custom_{$k}"] = $field;
1733 $members = array(array('member_id', '=', $membership->id
, 0, 0));
1734 // check whether its a test drive
1735 if ($form->_mode
== 'test') {
1736 $members[] = array('member_test', '=', 1, 0, 0);
1739 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1742 if (!empty($form->_params
['billing_first_name'])) {
1743 $name = $form->_params
['billing_first_name'];
1746 if (!empty($form->_params
['billing_middle_name'])) {
1747 $name .= " {$form->_params['billing_middle_name']}";
1750 if (!empty($form->_params
['billing_last_name'])) {
1751 $name .= " {$form->_params['billing_last_name']}";
1754 $form->assign('billingName', $name);
1756 // assign the address formatted up for display
1757 $addressParts = array(
1758 "street_address-{$form->_bltID}",
1759 "city-{$form->_bltID}",
1760 "postal_code-{$form->_bltID}",
1761 "state_province-{$form->_bltID}",
1762 "country-{$form->_bltID}",
1764 $addressFields = array();
1765 foreach ($addressParts as $part) {
1766 list($n, $id) = explode('-', $part);
1767 if (isset($form->_params
['billing_' . $part])) {
1768 $addressFields[$n] = $form->_params
['billing_' . $part];
1771 $form->assign('address', CRM_Utils_Address
::format($addressFields));
1773 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
1774 $date = CRM_Utils_Date
::mysqlToIso($date);
1775 $form->assign('credit_card_exp_date', $date);
1776 $form->assign('credit_card_number',
1777 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
1779 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
1780 $form->assign('contributeMode', 'direct');
1781 $form->assign('isAmountzero', 0);
1782 $form->assign('is_pay_later', 0);
1783 $form->assign('isPrimary', 1);
1786 $form->assign('module', 'Membership');
1787 $form->assign('contactID', $formValues['contact_id']);
1789 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
1791 if (!empty($formValues['contribution_id'])) {
1792 $form->assign('contributionID', $formValues['contribution_id']);
1794 elseif (isset($form->_onlinePendingContributionId
)) {
1795 $form->assign('contributionID', $form->_onlinePendingContributionId
);
1798 if (!empty($formValues['contribution_status_id'])) {
1799 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1800 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
1803 if (!empty($formValues['is_renew'])) {
1804 $form->assign('receiptType', 'membership renewal');
1807 $form->assign('receiptType', 'membership signup');
1809 $form->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $formValues)));
1810 $form->assign('formValues', $formValues);
1812 if (empty($lineItem)) {
1813 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1814 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
1815 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1817 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1820 $form->assign('customValues', $customValues);
1821 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1822 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1823 // in this case the form is being called statically from the batch editing screen
1824 // having one class in the form layer call another statically is not greate
1825 // & we should aim to move this function to the BAO layer in future.
1826 // however, we can assume that the contact_id passed in by the batch
1827 // function will be the recipient
1829 $form->_contributorDisplayName
,
1830 $form->_contributorEmail
1831 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails(
1832 $formValues['contact_id']
1834 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1835 $form->_receiptContactId
= $formValues['contact_id'];
1838 $template = CRM_Core_Smarty
::singleton( );
1839 $taxAmt = $template->get_template_vars('dataArray');
1840 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1841 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1842 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1843 if ((!empty($taxAmt) ||
isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1847 $isEmailPdf = False;
1850 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1852 'groupName' => 'msg_tpl_workflow_membership',
1853 'valueName' => 'membership_offline_receipt',
1854 'contactId' => $form->_receiptContactId
,
1855 'from' => $receiptFrom,
1856 'toName' => $form->_contributorDisplayName
,
1857 'toEmail' => $form->_contributorEmail
,
1858 'PDFFilename' => ts('receipt').'.pdf',
1859 'isEmailPdf' => $isEmailPdf,
1860 'contributionId' => $formValues['contribution_id'],
1861 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
)