3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 protected $_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);
115 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
116 $this->set('priceSetId', $this->_priceSetId
);
117 $this->assign('priceSetId', $this->_priceSetId
);
120 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
121 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
122 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
123 $this->_processors
= array();
124 CRM_Core_Resources
::singleton()->addSetting(array('ids' => array('contact' => $this->_contactID
)));
126 // check for edit permission
127 if (!CRM_Core_Permission
::checkActionPermission('CiviMember', $this->_action
)) {
128 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
131 if ($this->_action
& CRM_Core_Action
::DELETE
) {
132 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
133 // check delete permission for contribution
134 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
135 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."));
139 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
140 $this->assign('context', $this->_context
);
143 $this->_memType
= CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'membership_type_id');
144 $this->_membershipIDs
[] = $this->_id
;
147 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
148 $this->assign('membershipMode', $this->_mode
);
151 $this->_paymentProcessor
= array('billing_mode' => 1);
152 $validProcessors = array();
153 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'billing_mode IN ( 1, 3 )');
155 foreach ($processors as $ppID => $label) {
156 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($ppID, $this->_mode
);
157 if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
160 elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode
== 'live') {
164 $paymentObject = CRM_Core_Payment
::singleton($this->_mode
, $paymentProcessor, $this);
165 $error = $paymentObject->checkConfig();
167 $validProcessors[$ppID] = $label;
169 $paymentObject = NULL;
172 if (empty($validProcessors)) {
173 CRM_Core_Error
::fatal(ts('Could not find valid payment processor for this page'));
176 $this->_processors
= $validProcessors;
178 // also check for billing information
179 // get the billing location type
180 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
181 // CRM-8108 remove ts around Billing location type
182 //$this->_bltID = array_search( ts('Billing'), $locationTypes );
183 $this->_bltID
= array_search('Billing', $locationTypes);
184 if (!$this->_bltID
) {
185 CRM_Core_Error
::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
187 $this->set('bltID', $this->_bltID
);
188 $this->assign('bltID', $this->_bltID
);
190 $this->_fields
= array();
192 CRM_Core_Payment_Form
::setCreditCardFields($this);
194 // this required to show billing block
195 $this->assign_by_ref('paymentProcessor', $paymentProcessor);
196 $this->assign('hidePayPalExpress', TRUE);
199 if ($this->_action
& CRM_Core_Action
::ADD
) {
200 if (!CRM_Member_BAO_Membership
::statusAvailabilty($this->_contactID
)) {
201 // all possible statuses are disabled - redirect back to contact form
202 CRM_Core_Error
::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
205 if ($this->_contactID
) {
206 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
207 $contactMemberships = array();
208 $memParams = array('contact_id' => $this->_contactID
);
209 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
210 $cMemTypes = array();
211 foreach ($contactMemberships as $mem) {
212 $cMemTypes[] = $mem['membership_type_id'];
214 if (count($cMemTypes) > 0) {
215 $memberorgs = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($cMemTypes);
216 $mems_by_org = array();
217 foreach ($contactMemberships as $memid => $mem) {
218 $mem['member_of_contact_id'] = CRM_Utils_Array
::value($mem['membership_type_id'], $memberorgs);
219 if (CRM_Utils_Array
::value('membership_end_date', $mem)) {
220 $mem['membership_end_date'] = CRM_Utils_Date
::customformat($mem['membership_end_date']);
222 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
223 $mem['membership_type_id'],
226 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
231 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
232 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member&mode=live"
236 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
237 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
240 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
241 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
243 $mems_by_org[$mem['member_of_contact_id']] = $mem;
245 $resources = CRM_Core_Resources
::singleton();
246 $resources->addSetting(array('existingMems' => array('memberorgs' => $mems_by_org)));
247 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/Membership.js');
251 $resources = CRM_Core_Resources
::singleton();
252 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
254 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
255 $membershipStatus->is_current_member
= 1;
256 $membershipStatus->find();
257 $membershipStatus->selectAdd();
258 $membershipStatus->selectAdd('id');
259 while ($membershipStatus->fetch()) {
260 $statuses[$membershipStatus->id
] = $membershipStatus->label
;
262 $membershipStatus->free();
264 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
265 'memtypes' => CRM_Member_BAO_MembershipType
::getMembershipTypes(FALSE),
266 'statuses' => $statuses,
268 $resources->addSetting(array('existingMems' => $passthru));
272 // when custom data is included in this page
273 if (CRM_Utils_Array
::value('hidden_custom', $_POST)) {
274 CRM_Custom_Form_CustomData
::preProcess($this);
275 CRM_Custom_Form_CustomData
::buildQuickForm($this);
276 CRM_Custom_Form_CustomData
::setDefaultValues($this);
279 // CRM-4395, get the online pending contribution id.
280 $this->_onlinePendingContributionId
= NULL;
281 if (!$this->_mode
&& $this->_id
&& ($this->_action
& CRM_Core_Action
::UPDATE
)) {
282 $this->_onlinePendingContributionId
= CRM_Contribute_BAO_Contribution
::checkOnlinePendingContribution($this->_id
,
286 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId
);
287 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
290 if ($this->_contactID
) {
291 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_contactID
);
293 // Check if this is default domain contact CRM-10482
294 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_contactID
)) {
295 $displayName .= ' (' . ts('default organization') . ')';
298 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
299 CRM_Utils_System
::setTitle(ts('Membership for') . ' ' . $displayName);
301 parent
::preProcess();
305 * This function sets the default values for the form. MobileProvider that in edit/view mode
306 * the default values are retrieved from the database
312 public function setDefaultValues() {
313 if ($this->_cdType
) {
314 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
317 if ($this->_priceSetId
) {
318 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
321 $defaults = parent
::setDefaultValues();
323 //setting default join date and receive date
324 list($now, $currentTime) = CRM_Utils_Date
::setDateDefaults();
325 if ($this->_action
== CRM_Core_Action
::ADD
) {
326 $defaults['receive_date'] = $now;
327 $defaults['receive_date_time'] = $currentTime;
330 if (is_numeric($this->_memType
)) {
331 $defaults['membership_type_id'] = array();
332 $defaults['membership_type_id'][0] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
334 'member_of_contact_id',
337 $defaults['membership_type_id'][1] = $this->_memType
;
340 $defaults['membership_type_id'] = $this->_memType
;
343 $defaults['num_terms'] = 1;
345 if (CRM_Utils_Array
::value('id', $defaults)) {
346 if ($this->_onlinePendingContributionId
) {
347 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
350 $contributionId = CRM_Core_DAO
::singleValueQuery("
351 SELECT contribution_id
352 FROM civicrm_membership_payment
353 WHERE membership_id = $this->_id
354 ORDER BY contribution_id
357 if ($contributionId) {
358 $defaults['record_contribution'] = $contributionId;
363 if (CRM_Utils_Array
::value('record_contribution', $defaults) && !$this->_mode
) {
364 $contributionParams = array('id' => $defaults['record_contribution']);
365 $contributionIds = array();
367 //keep main object campaign in hand.
368 $memberCampaignId = CRM_Utils_Array
::value('campaign_id', $defaults);
370 CRM_Contribute_BAO_Contribution
::getValues($contributionParams, $defaults, $contributionIds);
372 //get back original object campaign id.
373 $defaults['campaign_id'] = $memberCampaignId;
375 if (CRM_Utils_Array
::value('receive_date', $defaults)) {
376 list($defaults['receive_date']) = CRM_Utils_Date
::setDateDefaults($defaults['receive_date']);
379 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
380 if (CRM_Utils_Array
::value('membership_source', $defaults)) {
381 $defaults['source'] = $defaults['membership_source'];
385 if (!CRM_Utils_Array
::value('payment_instrument_id', $defaults)) {
386 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
389 // User must explicitly choose to send a receipt in both add and update mode.
390 $defaults['send_receipt'] = 0;
392 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
393 // in this mode by default uncheck this checkbox
394 unset($defaults['record_contribution']);
397 if (CRM_Utils_Array
::value('id', $defaults)) {
398 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
401 $alreadyAutoRenew = FALSE;
402 if (CRM_Utils_Array
::value('contribution_recur_id', $defaults) && !$subscriptionCancelled) {
403 $defaults['auto_renew'] = 1;
404 $alreadyAutoRenew = TRUE;
406 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
408 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
410 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
412 if (CRM_Utils_Array
::value('is_pay_later', $defaults)) {
413 $this->assign('is_pay_later', TRUE);
416 // set default country from config if no country set
417 $config = CRM_Core_Config
::singleton();
418 if (!CRM_Utils_Array
::value("billing_country_id-{$this->_bltID}", $defaults)) {
419 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
422 if (!CRM_Utils_Array
::value("billing_state_province_id-{$this->_bltID}", $defaults)) {
423 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
426 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
427 $defaults = array_merge($defaults, $billingDefaults);
429 // now fix all state country selectors, set correct state based on country
430 CRM_Core_BAO_Address
::fixAllStateSelects($this, $defaults);
432 // // hack to simplify credit card entry for testing
433 // $defaults['credit_card_type'] = 'Visa';
434 // $defaults['credit_card_number'] = '4807731747657838';
435 // $defaults['cvv2'] = '000';
436 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
439 $dates = array('join_date', 'start_date', 'end_date');
440 foreach ($dates as $key) {
441 if (CRM_Utils_Array
::value($key, $defaults)) {
442 list($defaults[$key]) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults));
446 //setting default join date if there is no join date
447 if (!CRM_Utils_Array
::value('join_date', $defaults)) {
448 $defaults['join_date'] = $now;
451 if (CRM_Utils_Array
::value('membership_end_date', $defaults)) {
452 $this->assign('endDate', $defaults['membership_end_date']);
459 * Function to build the form
464 public function buildQuickForm() {
465 if ($this->_cdType
) {
466 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
469 // build price set form.
470 $buildPriceSet = FALSE;
471 if ($this->_priceSetId || CRM_Utils_Array
::value('price_set_id', $_POST)) {
472 if (CRM_Utils_Array
::value('price_set_id', $_POST)) {
473 $buildPriceSet = TRUE;
475 $getOnlyPriceSetElements = TRUE;
476 if (!$this->_priceSetId
) {
477 $this->_priceSetId
= $_POST['price_set_id'];
478 $getOnlyPriceSetElements = FALSE;
481 $this->set('priceSetId', $this->_priceSetId
);
482 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
484 $optionsMembershipTypes = array();
485 foreach ($this->_priceSet
['fields'] as $pField) {
486 if (empty($pField['options'])) {
489 foreach ($pField['options'] as $opId => $opValues) {
490 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
494 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
496 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
497 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
499 // get only price set form elements.
500 if ($getOnlyPriceSetElements) {
505 // use to build form during form rule.
506 $this->assign('buildPriceSet', $buildPriceSet);
508 if ($this->_action
& CRM_Core_Action
::ADD
) {
509 $buildPriceSet = FALSE;
510 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
511 if (!empty($priceSets)) {
512 $buildPriceSet = TRUE;
515 if ($buildPriceSet) {
516 $this->add('select', 'price_set_id', ts('Choose price set'),
518 '' => ts('Choose price set')
520 NULL, array('onchange' => "buildAmount( this.value );")
523 $this->assign('hasPriceSets', $buildPriceSet);
526 //need to assign custom data type and subtype to the template
527 $this->assign('customDataType', 'Membership');
528 $this->assign('customDataSubType', $this->_memType
);
529 $this->assign('entityID', $this->_id
);
531 if ($this->_action
& CRM_Core_Action
::DELETE
) {
532 $this->addButtons(array(
535 'name' => ts('Delete'),
536 'spacing' => ' ',
541 'name' => ts('Cancel'),
548 if ($this->_context
== 'standalone') {
549 CRM_Contact_Form_NewContact
::buildQuickForm($this);
552 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
554 $dao = new CRM_Member_DAO_MembershipType();
555 $dao->domain_id
= CRM_Core_Config
::domainID();
558 // retrieve all memberships
559 $allMemberships = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this);
561 $allMembershipInfo = $membershipType = array();
562 foreach ($allMemberships as $key => $values) {
563 if (CRM_Utils_Array
::value('is_active', $values)) {
564 $membershipType[$key] = CRM_Utils_Array
::value('name', $values);
565 if ($this->_mode
&& !CRM_Utils_Array
::value('minimum_fee', $values)) {
569 $memberOfContactId = CRM_Utils_Array
::value('member_of_contact_id', $values);
570 if (!CRM_Utils_Array
::value($memberOfContactId, $selMemTypeOrg)) {
571 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
577 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
579 if (!CRM_Utils_Array
::value($key, $selOrgMemType[$memberOfContactId])) {
580 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array
::value('name', $values);
584 // build membership info array, which is used when membership type is selected to:
585 // - set the payment information block
586 // - set the max related block
587 $allMembershipInfo[$key] = array(
588 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $values),
589 'total_amount' => CRM_Utils_Money
::format($values['minimum_fee'], NULL, '%a'),
590 'total_amount_numeric' => CRM_Utils_Array
::value('minimum_fee', $values),
591 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $values),
592 'has_related' => isset($values['relationship_type_id']),
593 'max_related' => CRM_Utils_Array
::value('max_related', $values),
598 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
600 // show organization by default, if only one organization in
602 if (count($selMemTypeOrg) == 2) {
603 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
605 //sort membership organization and type, CRM-6099
606 natcasesort($selMemTypeOrg);
607 foreach ($selOrgMemType as $index => $orgMembershipType) {
608 natcasesort($orgMembershipType);
609 $selOrgMemType[$index] = $orgMembershipType;
612 $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
614 //build the form for auto renew.
615 $recurProcessor = $autoRenew = array();
616 if ($this->_mode ||
($this->_action
& CRM_Core_Action
::UPDATE
)) {
617 $autoRenewElement = $this->addElement('checkbox',
619 ts('Membership renewed automatically'),
621 array('onclick' => "buildReceiptANDNotice( );")
625 //get the valid recurring processors.
626 $recurring = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
627 $recurProcessor = array_intersect_assoc($this->_processors
, $recurring);
628 $autoRenew = array();
629 if (!empty($recurProcessor)) {
630 if (!empty($membershipType)) {
636 FROM civicrm_membership_type
637 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
638 $recurMembershipTypes = CRM_Core_DAO
::executeQuery($sql);
639 while ($recurMembershipTypes->fetch()) {
640 $autoRenew[$recurMembershipTypes->id
] = $recurMembershipTypes->auto_renew
;
647 $this->_recurMembershipTypes
[$recurMembershipTypes->id
][$fld] = $recurMembershipTypes->$fld;
653 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
658 $allowAutoRenew = FALSE;
659 if ($this->_mode
&& !empty($recurProcessor)) {
660 $allowAutoRenew = TRUE;
662 $this->assign('allowAutoRenew', $allowAutoRenew);
663 $this->assign('autoRenewOptions', json_encode($autoRenew));
664 $this->assign('recurProcessor', json_encode($recurProcessor));
666 // for max_related: a little JS to show/hide & set default value
667 $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
668 $this->add('text', 'max_related', ts('Max related'),
669 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
672 $sel = & $this->addElement('hierselect',
673 'membership_type_id',
674 ts('Membership Organization and Type'),
678 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
684 $this->applyFilter('__ALL__', 'trim');
686 if ($this->_action
& CRM_Core_Action
::ADD
) {
687 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
690 $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
691 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
692 $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
694 $elements[] = $endDate;
697 $this->add('text', 'source', ts('Source'),
698 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
701 //CRM-7362 --add campaigns.
704 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
706 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
709 $this->add('select', 'status_id', ts('Membership Status'),
710 array('' => ts('- select -')) + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
712 $statusOverride = $this->addElement('checkbox', 'is_override',
713 ts('Status Override?'), NULL,
714 array('onClick' => 'showHideMemberStatus()')
716 if ($statusOverride) {
717 $elements[] = $statusOverride;
720 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
722 $this->add('text', 'total_amount', ts('Amount'));
723 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
725 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
727 $this->add('select', 'payment_instrument_id',
729 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
730 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
732 $this->add('text', 'trxn_id', ts('Transaction ID'));
733 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
734 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id
, 'trxn_id')
737 $allowStatuses = array();
738 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
739 if ($this->_onlinePendingContributionId
) {
740 $statusNames = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
741 foreach ($statusNames as $val => $name) {
742 if (in_array($name, array(
749 $allowStatuses[$val] = $statuses[$val];
753 $allowStatuses = $statuses;
755 $this->add('select', 'contribution_status_id',
756 ts('Payment Status'), $allowStatuses
758 $this->add('text', 'check_number', ts('Check Number'),
759 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
763 //add field for amount to allow an amount to be entered that differs from minimum
764 $this->add('text', 'total_amount', ts('Amount'));
766 $this->add('select', 'financial_type_id',
767 ts('Financial Type'),
768 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType()
770 if ($this->_context
!= 'standalone') {
771 //CRM-10223 - allow contribution to be recorded against different contact
772 // causes a conflict in standalone mode so skip in standalone for now
773 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
774 $this->add('select', 'soft_credit_type_id', ts('Membership payment is : '),
775 array('' => ts('- Select - ')) + CRM_Core_OptionGroup
::values("soft_credit_type", FALSE));
776 CRM_Contact_Form_NewContact
::buildQuickForm($this, 1, NULL, FALSE, 'contribution_');
779 $this->addElement('checkbox',
781 ts('Send Confirmation and Receipt?'), NULL,
782 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);")
785 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
787 $this->add('textarea', 'receipt_text_signup', ts('Receipt Message'));
790 $this->add('select', 'payment_processor_id',
791 ts('Payment Processor'),
792 $this->_processors
, TRUE,
793 array('onChange' => "buildAutoRenew( null, this.value );")
795 CRM_Core_Payment_Form
::buildCreditCard($this, TRUE);
798 // Retrieve the name and email of the contact - this will be the TO for receipt email
799 if ($this->_contactID
) {
800 list($this->_memberDisplayName
,
802 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
804 $this->assign('emailExists', $this->_memberEmail
);
805 $this->assign('displayName', $this->_memberDisplayName
);
809 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
810 $recurContributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
,
811 'contribution_recur_id'
813 if ($recurContributionId && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
)) {
815 if (CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
816 $this->assign('cancelAutoRenew',
817 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
820 foreach ($elements as $elem) {
825 $this->assign('isRecur', $isRecur);
827 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
829 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
832 $this->assign('outBound_option', $mailingInfo['outBound_option']);
834 parent
::buildQuickForm();
838 * Function for validation
840 * @param array $params (ref.) an assoc array of name/value pairs
842 * @return mixed true or array of errors
846 static function formRule($params, $files, $self) {
849 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
852 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
854 $priceFieldIDS = array();
855 foreach ($self->_priceSet
['fields'] as $priceIds => $dontCare) {
857 if (!empty($params['price_' . $priceIds])) {
858 if (is_array($params['price_' . $priceIds])) {
859 foreach ($params['price_' . $priceIds] as $priceFldVal => $isSet) {
861 $priceFieldIDS[] = $priceFldVal;
866 $priceFieldIDS[] = $params['price_' . $priceIds];
871 if (!empty($priceFieldIDS)) {
872 $ids = implode(',', $priceFieldIDS);
874 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
875 foreach ($count as $id => $occurance) {
876 if ($occurance > 1) {
877 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
881 foreach ($priceFieldIDS as $priceFieldId) {
882 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
883 $self->_memTypeSelected
[$id] = $id;
888 elseif (!CRM_Utils_Array
::value(1, $params['membership_type_id'])) {
889 $errors['membership_type_id'] = ts('Please select a membership type.');
892 $self->_memTypeSelected
[] = $params['membership_type_id'][1];
896 $numterms = CRM_Utils_Array
::value('num_terms', $params);
897 if ($numterms && intval($numterms) != $numterms) {
898 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
902 // Return error if empty $self->_memTypeSelected
903 if ($priceSetId && empty($errors) && empty($self->_memTypeSelected
)) {
904 $errors['_qf_default'] = ts('Select at least one membership option.');
907 if (!empty($errors) && (count($self->_memTypeSelected
) > 1)) {
908 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($self->_memTypeSelected
);
909 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
910 foreach ($duplicateMemberOfContacts as $countDuplicate) {
911 if ($countDuplicate > 1) {
912 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
917 //check if contact is selected in standalone mode
918 if (isset($params['contact_select_id'][1]) && !$params['contact_select_id'][1]) {
919 $errors['contact[1]'] = ts('Please select a contact or create new contact');
922 if (!empty($errors)) {
926 if ($priceSetId && !$self->_mode
&& !CRM_Utils_Array
::value('record_contribution', $params)) {
927 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
930 if (!$priceSetId && $self->_mode
&& !CRM_Utils_Array
::value('financial_type_id', $params)) {
931 $errors['financial_type_id'] = ts('Please enter the financial Type.');
934 if (CRM_Utils_Array
::value('record_contribution', $params) && !CRM_Utils_Array
::value('payment_instrument_id', $params)) {
935 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
938 if (CRM_Utils_Array
::value('is_different_contribution_contact', $params)) {
939 if (!CRM_Utils_Array
::value('soft_credit_type_id', $params)) {
940 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
942 if (!CRM_Utils_Array
::value(1, $params['contribution_contact'])) {
943 $errors['contribution_contact[1]'] = ts('Please select a contact');
947 if (CRM_Utils_Array
::value('payment_processor_id', $params)) {
948 // make sure that credit card number and cvv are valid
949 CRM_Core_Payment_Form
::validateCreditCard($params, $errors);
953 if (CRM_Utils_Array
::value('join_date', $params)) {
955 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
957 foreach ($self->_memTypeSelected
as $memType) {
959 if (CRM_Utils_Array
::value('start_date', $params)) {
960 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
963 // if end date is set, ensure that start date is also set
964 // and that end date is later than start date
965 // If selected membership type has duration unit as 'lifetime'
966 // and end date is set, then give error
968 if (CRM_Utils_Array
::value('end_date', $params)) {
969 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
972 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
974 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) == 'rolling') {
975 if ($startDate < $joinDate) {
976 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
981 if ($membershipDetails['duration_unit'] == 'lifetime') {
982 $errors['end_date'] = ts('The selected Membership Type has a lifetime duration. You cannot specify an End Date for lifetime memberships. Please clear the End Date OR select a different Membership Type.');
986 $errors['start_date'] = ts('Start date must be set if end date is set.');
988 if ($endDate < $startDate) {
989 $errors['end_date'] = ts('End date must be the same or later than start date.');
994 // Default values for start and end dates if not supplied
996 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1003 $startDate = CRM_Utils_Array
::value('start_date',
1008 $endDate = CRM_Utils_Array
::value('end_date',
1013 //CRM-3724, check for availability of valid membership status.
1014 if (!CRM_Utils_Array
::value('is_override', $params) && !isset($errors['_qf_default'])) {
1015 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
1021 if (empty($calcStatus)) {
1022 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
1023 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
1024 $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));
1025 if (!$self->_mode
) {
1026 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
1028 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
1034 $errors['join_date'] = ts('Please enter the Member Since.');
1037 if (isset($params['is_override']) &&
1038 $params['is_override'] &&
1039 !CRM_Utils_Array
::value('status_id', $params)
1041 $errors['status_id'] = ts('Please enter the status.');
1044 //total amount condition arise when membership type having no
1046 if (isset($params['record_contribution'])) {
1047 if (!$params['financial_type_id']) {
1048 $errors['financial_type_id'] = ts('Please enter the financial Type.');
1050 if (CRM_Utils_System
::isNull($params['total_amount'])) {
1051 $errors['total_amount'] = ts('Please enter the contribution.');
1055 // validate contribution status for 'Failed'.
1056 if ($self->_onlinePendingContributionId
&&
1057 CRM_Utils_Array
::value('record_contribution', $params) &&
1058 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
1059 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1062 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
1065 return empty($errors) ?
TRUE : $errors;
1069 * Function to process the form
1075 public function postProcess() {
1076 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1077 CRM_Member_BAO_Membership
::del($this->_id
);
1081 $config = CRM_Core_Config
::singleton();
1082 // get the submitted form values.
1083 $this->_params
= $formValues = $this->controller
->exportValues($this->_name
);
1084 $this->convertDateFieldsToMySQL($formValues);
1086 $params = $softParams = $ids = array();
1088 $membershipTypeValues = array();
1089 foreach ($this->_memTypeSelected
as $memType) {
1090 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1093 //take the required membership recur values.
1094 if ($this->_mode
&& CRM_Utils_Array
::value('auto_renew', $this->_params
)) {
1095 $params['is_recur'] = $this->_params
['is_recur'] = $formValues['is_recur'] = TRUE;
1097 'frequency_interval' => 'duration_interval',
1098 'frequency_unit' => 'duration_unit',
1102 foreach ($this->_memTypeSelected
as $memType) {
1103 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1104 $this->_recurMembershipTypes
, array()
1106 foreach ($mapping as $mapVal => $mapParam) {
1107 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array
::value($mapParam,
1108 $recurMembershipTypeValues
1111 $this->_params
[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1112 $recurMembershipTypeValues
1119 // unset send-receipt option, since receipt will be sent when ipn is received.
1120 unset($this->_params
['send_receipt'], $formValues['send_receipt']);
1123 // process price set and get total amount and line items.
1124 $lineItem = array();
1126 if (!$priceSetId = CRM_Utils_Array
::value('price_set_id', $formValues)) {
1127 CRM_Member_BAO_Membership
::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
1130 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1134 $termsByType = array();
1136 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1137 $this->_params
, $lineItem[$priceSetId]);
1138 $params['total_amount'] = CRM_Utils_Array
::value('amount', $this->_params
);
1139 $submittedFinancialType = CRM_Utils_Array
::value('financial_type_id', $formValues);
1140 if (!empty($lineItem[$priceSetId])) {
1141 foreach ($lineItem[$priceSetId] as &$li) {
1142 if (CRM_Utils_Array
::value('membership_type_id', $li)) {
1143 if (CRM_Utils_Array
::value('membership_num_terms', $li)) {
1144 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1148 ///CRM-11529 for quick config backoffice transactions
1149 //when financial_type_id is passed in form, update the
1150 //lineitems with the financial type selected in form
1151 if ($isQuickConfig && $submittedFinancialType) {
1152 $li['financial_type_id'] = $submittedFinancialType;
1158 $this->storeContactFields($formValues);
1160 $params['contact_id'] = $this->_contactID
;
1169 foreach ($fields as $f) {
1170 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1174 // when is_override false ignore is_admin statuses during membership
1175 // status calculation. similarly we did fix for import in CRM-3570.
1176 if (!CRM_Utils_Array
::value('is_override', $params)) {
1177 $params['exclude_is_admin'] = TRUE;
1180 // process date params to mysql date format.
1182 'join_date' => 'joinDate',
1183 'start_date' => 'startDate',
1184 'end_date' => 'endDate',
1186 foreach ($dateTypes as $dateField => $dateVariable) {
1187 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1190 $num_terms = CRM_Utils_Array
::value('num_terms', $formValues, 1);
1192 $calcDates = array();
1193 foreach ($this->_memTypeSelected
as $memType) {
1194 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, $num_terms);
1195 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1196 $joinDate, $startDate, $endDate, $memTypeNumTerms
1200 foreach ($calcDates as $memType => $calcDate) {
1201 foreach (array_keys($dateTypes) as $d) {
1202 //first give priority to form values then calDates.
1203 $date = CRM_Utils_Array
::value($d, $formValues);
1205 $date = CRM_Utils_Array
::value($d, $calcDate);
1208 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1209 //$params[$d] = CRM_Utils_Date::processDate( $date );
1213 // max related memberships - take from form or inherit from membership type
1214 foreach ($this->_memTypeSelected
as $memType) {
1215 if (array_key_exists('max_related', $formValues)) {
1216 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array
::value('max_related', $formValues);
1221 $ids['membership'] = $params['id'] = $this->_id
;
1224 $session = CRM_Core_Session
::singleton();
1225 $ids['userId'] = $session->get('userID');
1227 // membership type custom data
1228 foreach ($this->_memTypeSelected
as $memType) {
1229 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE,
1233 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
1234 CRM_Core_BAO_CustomField
::getFields('Membership',
1240 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1247 foreach ($this->_memTypeSelected
as $memType) {
1248 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1253 $membershipType = implode(', ', $membershipTypes);
1255 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1256 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($ids['userId']);
1258 //CRM-10223 - allow contribution to be recorded against different contact
1259 if ($this->_contributorContactID
!= $this->_contactID
) {
1260 $params['contribution_contact_id'] = $this->_contributorContactID
;
1261 if (CRM_Utils_Array
::value('soft_credit_type_id', $this->_params
)) {
1262 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1263 $softParams['contact_id'] = $params['contact_id'];
1266 if (CRM_Utils_Array
::value('record_contribution', $formValues)) {
1267 $recordContribution = array(
1269 'financial_type_id',
1270 'payment_instrument_id',
1272 'contribution_status_id',
1278 foreach ($recordContribution as $f) {
1279 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1282 if (!$this->_onlinePendingContributionId
) {
1283 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)',
1284 array(1 => $membershipType, 2 => $userName)
1288 if (!CRM_Utils_Array
::value('is_override', $params) &&
1289 CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1291 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1292 $params['status_id'] = array_search('Pending', $allStatus);
1293 $params['skipStatusCal'] = TRUE;
1294 $params['is_pay_later'] = 1;
1295 $this->assign('is_pay_later', 1);
1298 if (CRM_Utils_Array
::value('send_receipt', $formValues)) {
1299 $params['receipt_date'] = CRM_Utils_Array
::value('receive_date', $formValues);
1302 //insert financial type name in receipt.
1303 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1304 $formValues['financial_type_id']
1308 // process line items, until no previous line items.
1309 if (!empty($lineItem)) {
1310 $params['lineItems'] = $lineItem;
1311 $params['processPriceSet'] = TRUE;
1313 $createdMemberships = array();
1315 if (empty($formValues['total_amount']) && !$priceSetId) {
1316 // if total amount not provided minimum for membership type is used
1317 $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1318 $formValues['membership_type_id'][1], 'minimum_fee'
1322 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1325 if ($priceSetId && !$isQuickConfig) {
1326 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1332 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $formValues);
1335 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($formValues['payment_processor_id'],
1339 //get the payment processor id as per mode.
1340 $params['payment_processor_id'] = $this->_params
['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1343 $now = date('YmdHis');
1346 // set email for primary location.
1347 $fields['email-Primary'] = 1;
1348 $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail
;
1349 $params['register_date'] = $now;
1351 // now set the values for the billing location.
1352 foreach ($this->_fields
as $name => $dontCare) {
1356 // also add location name to the array
1357 $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);
1359 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1361 $fields["address_name-{$this->_bltID}"] = 1;
1362 //ensure we don't over-write the payer's email with the member's email
1363 if ($this->_contributorContactID
== $this->_contactID
) {
1364 $fields["email-{$this->_bltID}"] = 1;
1367 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type');
1369 $nameFields = array('first_name', 'middle_name', 'last_name');
1371 foreach ($nameFields as $name) {
1373 if (array_key_exists("billing_$name", $formValues)) {
1374 $formValues[$name] = $formValues["billing_{$name}"];
1375 $formValues['preserveDBName'] = TRUE;
1378 if ($this->_contributorContactID
== $this->_contactID
) {
1379 //see CRM-12869 for discussion of why we don't do this for separate payee payments
1380 CRM_Contact_BAO_Contact
::createProfileContact($formValues, $fields,
1381 $this->_contributorContactID
, NULL, NULL, $ctype
1385 // add all the additioanl payment params we need
1386 $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}"]);
1387 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1389 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1390 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1391 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1392 $this->_params
['amount'] = $params['total_amount'];
1393 $this->_params
['currencyID'] = $config->defaultCurrency
;
1394 $this->_params
['payment_action'] = 'Sale';
1395 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1396 $this->_params
['financial_type_id'] = $params['financial_type_id'];
1398 // at this point we've created a contact and stored its address etc
1399 // all the payment processors expect the name and address to be in the
1400 // so we copy stuff over to first_name etc.
1401 $paymentParams = $this->_params
;
1402 $paymentParams['contactID'] = $this->_contributorContactID
;
1403 //CRM-10377 if payment is by an alternate contact then we need to set that person
1404 // as the contact in the payment params
1405 if ($this->_contributorContactID
!= $this->_contactID
) {
1406 if (CRM_Utils_Array
::value('soft_credit_type_id', $this->_params
)) {
1407 $softParams['contact_id'] = $params['contact_id'];
1408 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1411 if (CRM_Utils_Array
::value('send_receipt', $this->_params
)) {
1412 $paymentParams['email'] = $this->_contributorEmail
;
1415 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1417 // CRM-7137 -for recurring membership,
1418 // we do need contribution and recuring records.
1420 if (CRM_Utils_Array
::value('is_recur', $paymentParams)) {
1421 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1423 $contributionType = new CRM_Financial_DAO_FinancialType();
1424 $contributionType->id
= $params['financial_type_id'];
1425 if (!$contributionType->find(TRUE)) {
1426 CRM_Core_Error
::fatal('Could not find a system table');
1429 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1432 $this->_contributorContactID
,
1439 //create new soft-credit record, CRM-13981
1440 $softParams['contribution_id'] = $contribution->id
;
1441 $softParams['currency'] = $contribution->currency
;
1442 $softParams['amount'] = $contribution->total_amount
;
1443 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1445 $paymentParams['contactID'] = $contactID;
1446 $paymentParams['contributionID'] = $contribution->id
;
1447 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1448 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1449 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1450 $ids['contribution'] = $contribution->id
;
1451 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1452 $params['status_id'] = array_search('Pending', $allStatus);
1453 $params['skipStatusCal'] = TRUE;
1455 //as membership is pending set dates to null.
1456 $memberDates = array(
1457 'join_date' => 'joinDate',
1458 'start_date' => 'startDate',
1459 'end_date' => 'endDate',
1462 foreach ($memberDates as $dp => $dv) {
1464 foreach ($this->_memTypeSelected
as $memType) {
1465 $membershipTypeValues[$memType][$dv] = NULL;
1470 if ($params['total_amount'] > 0.0) {
1471 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this);
1472 $result = & $payment->doDirectPayment($paymentParams);
1475 if (is_a($result, 'CRM_Core_Error')) {
1476 //make sure to cleanup db for recurring case.
1477 if (CRM_Utils_Array
::value('contributionID', $paymentParams)) {
1478 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1480 if (CRM_Utils_Array
::value('contributionRecurID', $paymentParams)) {
1481 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1484 CRM_Core_Error
::displaySessionError($result);
1485 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1486 "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
1491 $this->_params
= array_merge($this->_params
, $result);
1492 //assign amount to template if payment was successful
1493 $this->assign('amount', $params['total_amount']);
1496 $params['contribution_status_id'] = CRM_Utils_Array
::value('is_recur', $paymentParams) ?
2 : 1;
1497 $params['receive_date'] = $now;
1498 $params['invoice_id'] = $this->_params
['invoiceID'];
1499 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1500 array(1 => $membershipType, 2 => $userName)
1502 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1503 $params['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1504 $params['payment_instrument_id'] = 1;
1505 $params['is_test'] = ($this->_mode
== 'live') ?
0 : 1;
1506 if (CRM_Utils_Array
::value('send_receipt', $this->_params
)) {
1507 $params['receipt_date'] = $now;
1510 $params['receipt_date'] = NULL;
1513 $this->set('params', $this->_params
);
1514 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1515 $this->assign('receive_date',
1516 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1519 // required for creating membership for related contacts
1520 $params['action'] = $this->_action
;
1522 //create membership record.
1524 foreach ($this->_memTypeSelected
as $memType) {
1526 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1528 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1531 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1532 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1534 $this->_membershipIDs
[] = $membership->id
;
1535 $createdMemberships[$memType] = $membership;
1541 $params['action'] = $this->_action
;
1542 if ($this->_onlinePendingContributionId
&&
1543 CRM_Utils_Array
::value('record_contribution', $formValues)
1546 // update membership as well as contribution object, CRM-4395
1547 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1548 $params['componentId'] = $params['id'];
1549 $params['componentName'] = 'contribute';
1550 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1551 if (!empty($result) && CRM_Utils_Array
::value('contribution_id', $params)) {
1552 $lineItem = array();
1553 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($params['contribution_id'], 'contribution');
1554 $itemId = key($lineItems);
1555 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1557 if ($itemId && CRM_Utils_Array
::value('price_field_id', $lineItems[$itemId])) {
1558 $fieldType = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1560 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1561 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1562 $lineItems[$itemId]['id'] = $itemId;
1563 $lineItem[$priceSetId] = $lineItems;
1564 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem);
1566 //create new soft-credit record, CRM-13981
1567 $softParams['contribution_id'] = $params['contribution_id'];
1568 $dao = new CRM_Contribute_DAO_Contribution();
1569 $dao->id
= $params['contribution_id'];
1571 while ($dao->fetch()) {
1572 $softParams['currency'] = $dao->currency
;
1573 $softParams['amount'] = $dao->total_amount
;
1575 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1578 //carry updated membership object.
1579 $membership = new CRM_Member_DAO_Membership();
1580 $membership->id
= $this->_id
;
1581 $membership->find(TRUE);
1584 if ($membership->end_date
) {
1585 //display end date w/ status message.
1586 $endDate = $membership->end_date
;
1588 $membershipStatues = CRM_Member_PseudoConstant
::membershipStatus();
1589 if (!in_array($membership->status_id
, array(
1590 array_search('Cancelled', $membershipStatues),
1591 array_search('Expired', $membershipStatues),
1597 // suppress form values in template.
1598 $this->assign('cancelled', $cancelled);
1600 // FIX ME: need to recheck this
1601 // here we might updated dates, so get from object.
1602 foreach ($calcDates[$membership->membership_type_id
] as $date => & $val) {
1603 if ($membership->$date) {
1604 $val = $membership->$date;
1608 $createdMemberships[] = $membership;
1612 foreach ($this->_memTypeSelected
as $memType) {
1614 CRM_Utils_Array
::value('record_contribution', $formValues) &&
1615 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1617 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1620 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1621 if (CRM_Utils_Array
::value('int_amount', $formValues)) {
1622 $init_amount = array();
1623 foreach ($formValues as $key => $value) {
1624 if (strstr($key, 'txt-price')) {
1625 $init_amount[$key] = $value;
1628 $membershipParams['init_amount'] = $init_amount;
1630 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1632 $this->_membershipIDs
[] = $membership->id
;
1633 $createdMemberships[$memType] = $membership;
1639 if (!empty($lineItem[$priceSetId])) {
1640 foreach ($lineItem[$priceSetId] as & $priceFieldOp) {
1641 if (CRM_Utils_Array
::value('membership_type_id', $priceFieldOp)) {
1642 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date
::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%d%f %b, %Y') : '-';
1644 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date
::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%d%f %b, %Y') : '-';
1647 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1651 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1653 $receiptSend = FALSE;
1654 if (CRM_Utils_Array
::value('send_receipt', $formValues)) {
1655 $receiptSend = TRUE;
1657 $formValues['contact_id'] = $this->_contactID
;
1659 // send email receipt
1660 $mailSend = self
::emailReceipt($this, $formValues, $membership);
1663 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1664 //end date can be modified by hooks, so if end date is set then use it.
1665 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1667 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName
));
1668 if ($endDate && $endDate !== 'null') {
1669 $endDate = CRM_Utils_Date
::customFormat($endDate);
1670 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
1673 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1676 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1677 // FIX ME: fix status messages
1679 $statusMsg = array();
1680 foreach ($membershipTypes as $memType => $membershipType) {
1681 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1682 1 => $membershipType,
1683 2 => $this->_memberDisplayName
1686 $membership = $createdMemberships[$memType];
1687 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1689 //get the end date from calculated dates.
1690 if (!$memEndDate && !CRM_Utils_Array
::value('is_recur', $params)) {
1691 $memEndDate = CRM_Utils_Array
::value('end_date', $calcDates[$memType]);
1694 if ($memEndDate && $memEndDate !== 'null') {
1695 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1696 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
1699 $statusMsg = implode('<br/>', $statusMsg);
1700 if ($receiptSend && $mailSend) {
1701 $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1705 // finally set membership id if already not set
1707 $this->_id
= $membership->id
;
1710 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1712 $buttonName = $this->controller
->getButtonName();
1713 if ($this->_context
== 'standalone') {
1714 if ($buttonName == $this->getButtonName('upload', 'new')) {
1715 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1716 'reset=1&action=add&context=standalone'
1720 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1721 "reset=1&cid={$this->_contactID}&selectedChild=member"
1725 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1726 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1727 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1733 * Function to send email receipt
1735 * @param object $form form object
1736 * @param array $values submitted values
1737 * @param object $membership object
1739 * @return boolean true if mail was sent successfully
1742 static function emailReceipt(&$form, &$formValues, &$membership) {
1743 // retrieve 'from email id' for acknowledgement
1744 $receiptFrom = $formValues['from_email_address'];
1746 if (CRM_Utils_Array
::value('payment_instrument_id', $formValues)) {
1747 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
1748 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1751 // retrieve custom data
1752 $customFields = $customValues = array();
1753 if (property_exists($form, '_groupTree')
1754 && !empty($form->_groupTree
)
1756 foreach ($form->_groupTree
as $groupID => $group) {
1757 if ($groupID == 'info') {
1760 foreach ($group['fields'] as $k => $field) {
1761 $field['title'] = $field['label'];
1762 $customFields["custom_{$k}"] = $field;
1767 $members = array(array('member_id', '=', $membership->id
, 0, 0));
1768 // check whether its a test drive
1769 if ($form->_mode
== 'test') {
1770 $members[] = array('member_test', '=', 1, 0, 0);
1773 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1776 if (CRM_Utils_Array
::value('billing_first_name', $form->_params
)) {
1777 $name = $form->_params
['billing_first_name'];
1780 if (CRM_Utils_Array
::value('billing_middle_name', $form->_params
)) {
1781 $name .= " {$form->_params['billing_middle_name']}";
1784 if (CRM_Utils_Array
::value('billing_last_name', $form->_params
)) {
1785 $name .= " {$form->_params['billing_last_name']}";
1788 $form->assign('billingName', $name);
1790 // assign the address formatted up for display
1791 $addressParts = array(
1792 "street_address-{$form->_bltID}",
1793 "city-{$form->_bltID}",
1794 "postal_code-{$form->_bltID}",
1795 "state_province-{$form->_bltID}",
1796 "country-{$form->_bltID}",
1798 $addressFields = array();
1799 foreach ($addressParts as $part) {
1800 list($n, $id) = explode('-', $part);
1801 if (isset($form->_params
['billing_' . $part])) {
1802 $addressFields[$n] = $form->_params
['billing_' . $part];
1805 $form->assign('address', CRM_Utils_Address
::format($addressFields));
1807 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
1808 $date = CRM_Utils_Date
::mysqlToIso($date);
1809 $form->assign('credit_card_exp_date', $date);
1810 $form->assign('credit_card_number',
1811 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
1813 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
1814 $form->assign('contributeMode', 'direct');
1815 $form->assign('isAmountzero', 0);
1816 $form->assign('is_pay_later', 0);
1817 $form->assign('isPrimary', 1);
1820 $form->assign('module', 'Membership');
1821 $form->assign('contactID', $formValues['contact_id']);
1823 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
1825 if (CRM_Utils_Array
::value('contribution_id', $formValues)) {
1826 $form->assign('contributionID', $formValues['contribution_id']);
1828 elseif (isset($form->_onlinePendingContributionId
)) {
1829 $form->assign('contributionID', $form->_onlinePendingContributionId
);
1832 if (CRM_Utils_Array
::value('contribution_status_id', $formValues)) {
1833 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1834 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
1837 if (CRM_Utils_Array
::value('is_renew', $formValues)) {
1838 $form->assign('receiptType', 'membership renewal');
1841 $form->assign('receiptType', 'membership signup');
1843 $form->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $formValues)));
1844 $form->assign('formValues', $formValues);
1846 if (empty($lineItem)) {
1847 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1848 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1849 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1852 $form->assign('customValues', $customValues);
1853 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1854 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1855 // in this case the form is being called statically from the batch editing screen
1856 // having one class in the form layer call another statically is not greate
1857 // & we should aim to move this function to the BAO layer in future.
1858 // however, we can assume that the contact_id passed in by the batch
1859 // function will be the recipient
1861 $form->_contributorDisplayName
,
1862 $form->_contributorEmail
1863 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails(
1864 $formValues['contact_id']
1866 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1867 $form->_receiptContactId
= $formValues['contact_id'];
1871 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1873 'groupName' => 'msg_tpl_workflow_membership',
1874 'valueName' => 'membership_offline_receipt',
1875 'contactId' => $form->_receiptContactId
,
1876 'from' => $receiptFrom,
1877 'toName' => $form->_contributorDisplayName
,
1878 'toEmail' => $form->_contributorEmail
,
1879 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
)