3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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.
59 protected $_memberDisplayName = NULL;
62 * email of the person paying for the membership (used for receipts)
64 protected $_memberEmail = NULL;
67 * Contact ID of the member.
71 public $_contactID = NULL;
74 * Display name of the person paying for the membership (used for receipts)
78 protected $_contributorDisplayName = NULL;
81 * email of the person paying for the membership (used for receipts)
83 protected $_contributorEmail = NULL;
86 * email of the person paying for the membership (used for receipts)
90 protected $_contributorContactID = NULL;
93 * ID of the person the receipt is to go to.
97 protected $_receiptContactId = NULL;
100 * Keep a class variable for ALL membeshipID's so
101 * postProcess hook function can do something with it
105 protected $_membershipIDs = array();
108 * An array to hold a list of datefields on the form
109 * so that they can be converted to ISO in a consistent manner
113 protected $_dateFields = array(
114 'receive_date' => array('default' => 'now'),
118 * Get selected membership type from the form values.
120 * @param int $priceSetID
121 * @param array $params
125 public static function getSelectedMemberships($priceSetID, $params) {
126 $memTypeSelected = array();
127 $priceFieldIDS = self
::getPriceFieldIDs($params);
128 if ($priceSetID && is_array($priceFieldIDS)) {
129 foreach ($priceFieldIDS as $priceFieldId) {
130 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
131 $memTypeSelected[$id] = $id;
136 $memTypeSelected = $params['membership_type_id'];
138 return $memTypeSelected;
142 * Extract price set fields and values from $params.
147 public static function getPriceFieldIDs($params) {
148 $priceFieldIDS = $priceSet = $fieldIds = array();
149 if (isset(self
::$priceSet) && is_array(self
::$priceSet)) {
150 $priceSet = self
::$_priceSet;
151 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
152 $fieldIds = array_keys($priceSet['fields']);
155 foreach ($fieldIds as $fieldId) {
156 if (!empty($params['price_' . $fieldId])) {
157 if (is_array($params['price_' . $fieldId])) {
158 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
160 $priceFieldIDS[] = $priceFldVal;
165 $priceFieldIDS[] = $params['price_' . $fieldId];
169 return $priceFieldIDS;
172 public function preProcess() {
173 //custom data related code
174 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
175 $this->assign('cdType', FALSE);
176 if ($this->_cdType
) {
177 $this->assign('cdType', TRUE);
178 return CRM_Custom_Form_CustomData
::preProcess($this);
181 parent
::preProcess();
183 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
184 $this->set('priceSetId', $this->_priceSetId
);
185 $this->assign('priceSetId', $this->_priceSetId
);
187 // check for edit permission
188 if (!CRM_Core_Permission
::checkActionPermission('CiviMember', $this->_action
)) {
189 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
192 if ($this->_action
& CRM_Core_Action
::DELETE
) {
193 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
194 // check delete permission for contribution
195 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
196 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."));
200 if ($this->_action
& CRM_Core_Action
::ADD
) {
201 if (!CRM_Member_BAO_Membership
::statusAvailabilty($this->_contactID
)) {
202 // all possible statuses are disabled - redirect back to contact form
203 CRM_Core_Error
::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
206 if ($this->_contactID
) {
207 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
208 $contactMemberships = array();
209 $memParams = array('contact_id' => $this->_contactID
);
210 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
211 $cMemTypes = array();
212 foreach ($contactMemberships as $mem) {
213 $cMemTypes[] = $mem['membership_type_id'];
215 if (count($cMemTypes) > 0) {
216 $memberorgs = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($cMemTypes);
217 $mems_by_org = array();
218 foreach ($contactMemberships as $mem) {
219 $mem['member_of_contact_id'] = CRM_Utils_Array
::value($mem['membership_type_id'], $memberorgs);
220 if (!empty($mem['membership_end_date'])) {
221 $mem['membership_end_date'] = CRM_Utils_Date
::customformat($mem['membership_end_date']);
223 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
224 $mem['membership_type_id'],
227 $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"
233 . ($this->_mode ?
'&mode=live' : '')
235 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
236 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
238 $mems_by_org[$mem['member_of_contact_id']] = $mem;
240 $this->assign('existingContactMemberships', $mems_by_org);
244 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
245 $resources = CRM_Core_Resources
::singleton();
246 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
248 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
249 'memtypes' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'membership_type_id'),
250 'statuses' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'status_id'),
252 $resources->addSetting(array('existingMems' => $passthru));
256 // when custom data is included in this page
257 if (!empty($_POST['hidden_custom'])) {
258 CRM_Custom_Form_CustomData
::preProcess($this);
259 CRM_Custom_Form_CustomData
::buildQuickForm($this);
260 CRM_Custom_Form_CustomData
::setDefaultValues($this);
263 // CRM-4395, get the online pending contribution id.
264 $this->_onlinePendingContributionId
= NULL;
265 if (!$this->_mode
&& $this->_id
&& ($this->_action
& CRM_Core_Action
::UPDATE
)) {
266 $this->_onlinePendingContributionId
= CRM_Contribute_BAO_Contribution
::checkOnlinePendingContribution($this->_id
,
270 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId
);
272 $this->setPageTitle(ts('Membership'));
276 * Set default values for the form. MobileProvider that in edit/view mode
277 * the default values are retrieved from the database
282 public function setDefaultValues() {
283 if ($this->_cdType
) {
284 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
287 if ($this->_priceSetId
) {
288 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
291 $defaults = parent
::setDefaultValues();
293 //setting default join date and receive date
294 list($now, $currentTime) = CRM_Utils_Date
::setDateDefaults();
295 if ($this->_action
== CRM_Core_Action
::ADD
) {
296 $defaults['receive_date'] = $now;
297 $defaults['receive_date_time'] = $currentTime;
300 if (is_numeric($this->_memType
)) {
301 $defaults['membership_type_id'] = array();
302 $defaults['membership_type_id'][0] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
304 'member_of_contact_id',
307 $defaults['membership_type_id'][1] = $this->_memType
;
310 $defaults['membership_type_id'] = $this->_memType
;
313 $defaults['num_terms'] = 1;
315 if (!empty($defaults['id'])) {
316 if ($this->_onlinePendingContributionId
) {
317 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
320 $contributionId = CRM_Core_DAO
::singleValueQuery("
321 SELECT contribution_id
322 FROM civicrm_membership_payment
323 WHERE membership_id = $this->_id
324 ORDER BY contribution_id
327 if ($contributionId) {
328 $defaults['record_contribution'] = $contributionId;
333 //set Soft Credit Type to Gift by default
334 $scTypes = CRM_Core_OptionGroup
::values("soft_credit_type");
335 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
337 if (!empty($defaults['record_contribution']) && !$this->_mode
) {
338 $contributionParams = array('id' => $defaults['record_contribution']);
339 $contributionIds = array();
341 //keep main object campaign in hand.
342 $memberCampaignId = CRM_Utils_Array
::value('campaign_id', $defaults);
344 CRM_Contribute_BAO_Contribution
::getValues($contributionParams, $defaults, $contributionIds);
346 //get back original object campaign id.
347 $defaults['campaign_id'] = $memberCampaignId;
349 if (!empty($defaults['receive_date'])) {
350 list($defaults['receive_date']) = CRM_Utils_Date
::setDateDefaults($defaults['receive_date']);
353 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
354 if (!empty($defaults['membership_source'])) {
355 $defaults['source'] = $defaults['membership_source'];
359 if (empty($defaults['payment_instrument_id'])) {
360 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
363 // User must explicitly choose to send a receipt in both add and update mode.
364 $defaults['send_receipt'] = 0;
366 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
367 // in this mode by default uncheck this checkbox
368 unset($defaults['record_contribution']);
371 $subscriptionCancelled = FALSE;
372 if (!empty($defaults['id'])) {
373 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
376 $alreadyAutoRenew = FALSE;
377 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
378 $defaults['auto_renew'] = 1;
379 $alreadyAutoRenew = TRUE;
381 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
383 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
385 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
387 if (!empty($defaults['is_pay_later'])) {
388 $this->assign('is_pay_later', TRUE);
391 // set default country from config if no country set
392 $config = CRM_Core_Config
::singleton();
393 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
394 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
397 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
398 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
401 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
402 $defaults = array_merge($defaults, $billingDefaults);
404 // // hack to simplify credit card entry for testing
405 // $defaults['credit_card_type'] = 'Visa';
406 // $defaults['credit_card_number'] = '4807731747657838';
407 // $defaults['cvv2'] = '000';
408 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
411 $dates = array('join_date', 'start_date', 'end_date');
412 foreach ($dates as $key) {
413 if (!empty($defaults[$key])) {
414 list($defaults[$key]) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults));
418 //setting default join date if there is no join date
419 if (empty($defaults['join_date'])) {
420 $defaults['join_date'] = $now;
423 if (!empty($defaults['membership_end_date'])) {
424 $this->assign('endDate', $defaults['membership_end_date']);
431 * Build the form object.
435 public function buildQuickForm() {
436 if ($this->_cdType
) {
437 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
440 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
441 $config = CRM_Core_Config
::singleton();
442 $this->assign('currency', $config->defaultCurrencySymbol
);
443 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
444 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
445 if (isset($invoicing)) {
446 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
448 // build price set form.
449 $buildPriceSet = FALSE;
450 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
451 if (!empty($_POST['price_set_id'])) {
452 $buildPriceSet = TRUE;
454 $getOnlyPriceSetElements = TRUE;
455 if (!$this->_priceSetId
) {
456 $this->_priceSetId
= $_POST['price_set_id'];
457 $getOnlyPriceSetElements = FALSE;
460 $this->set('priceSetId', $this->_priceSetId
);
461 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
463 $optionsMembershipTypes = array();
464 foreach ($this->_priceSet
['fields'] as $pField) {
465 if (empty($pField['options'])) {
468 foreach ($pField['options'] as $opId => $opValues) {
469 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
473 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
475 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
476 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
478 // get only price set form elements.
479 if ($getOnlyPriceSetElements) {
484 // use to build form during form rule.
485 $this->assign('buildPriceSet', $buildPriceSet);
487 if ($this->_action
& CRM_Core_Action
::ADD
) {
488 $buildPriceSet = FALSE;
489 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
490 if (!empty($priceSets)) {
491 $buildPriceSet = TRUE;
494 if ($buildPriceSet) {
495 $this->add('select', 'price_set_id', ts('Choose price set'),
497 '' => ts('Choose price set'),
499 NULL, array('onchange' => "buildAmount( this.value );")
502 $this->assign('hasPriceSets', $buildPriceSet);
505 //need to assign custom data type and subtype to the template
506 $this->assign('customDataType', 'Membership');
507 $this->assign('customDataSubType', $this->_memType
);
508 $this->assign('entityID', $this->_id
);
510 if ($this->_action
& CRM_Core_Action
::DELETE
) {
511 $this->addButtons(array(
514 'name' => ts('Delete'),
515 'spacing' => ' ',
520 'name' => ts('Cancel'),
527 if ($this->_context
== 'standalone') {
528 $this->addEntityRef('contact_id', ts('Contact'), array(
530 'api' => array('extra' => array('email')),
534 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
536 $dao = new CRM_Member_DAO_MembershipType();
537 $dao->domain_id
= CRM_Core_Config
::domainID();
540 // retrieve all memberships
541 $allMemberships = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this);
543 $allMembershipInfo = $membershipType = array();
544 foreach ($allMemberships as $key => $values) {
545 if (!empty($values['is_active'])) {
546 $membershipType[$key] = CRM_Utils_Array
::value('name', $values);
547 if ($this->_mode
&& empty($values['minimum_fee'])) {
551 $memberOfContactId = CRM_Utils_Array
::value('member_of_contact_id', $values);
552 if (empty($selMemTypeOrg[$memberOfContactId])) {
553 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
559 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
561 if (empty($selOrgMemType[$memberOfContactId][$key])) {
562 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array
::value('name', $values);
566 // build membership info array, which is used when membership type is selected to:
567 // - set the payment information block
568 // - set the max related block
569 $allMembershipInfo[$key] = array(
570 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $values),
571 'total_amount' => CRM_Utils_Money
::format($values['minimum_fee'], NULL, '%a'),
572 'total_amount_numeric' => CRM_Utils_Array
::value('minimum_fee', $values),
573 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $values),
574 'has_related' => isset($values['relationship_type_id']),
575 'max_related' => CRM_Utils_Array
::value('max_related', $values),
580 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
582 // show organization by default, if only one organization in
584 if (count($selMemTypeOrg) == 2) {
585 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
587 //sort membership organization and type, CRM-6099
588 natcasesort($selMemTypeOrg);
589 foreach ($selOrgMemType as $index => $orgMembershipType) {
590 natcasesort($orgMembershipType);
591 $selOrgMemType[$index] = $orgMembershipType;
594 $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
596 //build the form for auto renew.
597 $recurProcessor = $autoRenew = array();
598 if ($this->_mode ||
($this->_action
& CRM_Core_Action
::UPDATE
)) {
599 $autoRenewElement = $this->addElement('checkbox',
601 ts('Membership renewed automatically'),
603 array('onclick' => "buildReceiptANDNotice( );")
607 //get the valid recurring processors.
608 $test = strtolower($this->_mode
) == 'test' ?
TRUE : FALSE;
609 $recurring = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, $test, 'is_recur = 1');
610 $recurProcessor = array_intersect_assoc($this->_processors
, $recurring);
611 $autoRenew = array();
612 if (!empty($recurProcessor)) {
613 if (!empty($membershipType)) {
619 FROM civicrm_membership_type
620 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
621 $recurMembershipTypes = CRM_Core_DAO
::executeQuery($sql);
622 while ($recurMembershipTypes->fetch()) {
623 $autoRenew[$recurMembershipTypes->id
] = $recurMembershipTypes->auto_renew
;
630 $this->_recurMembershipTypes
[$recurMembershipTypes->id
][$fld] = $recurMembershipTypes->$fld;
636 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
641 $allowAutoRenew = FALSE;
642 if ($this->_mode
&& !empty($recurProcessor)) {
643 $allowAutoRenew = TRUE;
645 $this->assign('allowAutoRenew', $allowAutoRenew);
646 $this->assign('autoRenewOptions', json_encode($autoRenew));
647 $this->assign('recurProcessor', json_encode($recurProcessor));
649 // for max_related: a little JS to show/hide & set default value
650 $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
651 $this->add('text', 'max_related', ts('Max related'),
652 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
655 $sel = &$this->addElement('hierselect',
656 'membership_type_id',
657 ts('Membership Organization and Type'),
661 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
667 $this->applyFilter('__ALL__', 'trim');
669 if ($this->_action
& CRM_Core_Action
::ADD
) {
670 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
673 $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
674 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
675 $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
677 $elements[] = $endDate;
680 $this->add('text', 'source', ts('Source'),
681 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
684 //CRM-7362 --add campaigns.
687 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
689 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
692 $this->add('select', 'status_id', ts('Membership Status'),
693 array('' => ts('- select -')) + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
695 $statusOverride = $this->addElement('checkbox', 'is_override',
696 ts('Status Override?'), NULL,
697 array('onClick' => 'showHideMemberStatus()')
699 if ($statusOverride) {
700 $elements[] = $statusOverride;
703 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
705 $this->add('text', 'total_amount', ts('Amount'));
706 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
708 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
710 $this->add('select', 'payment_instrument_id',
712 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
713 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
715 $this->add('text', 'trxn_id', ts('Transaction ID'));
716 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
717 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id
, 'trxn_id')
720 $allowStatuses = array();
721 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
722 if ($this->_onlinePendingContributionId
) {
723 $statusNames = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
724 foreach ($statusNames as $val => $name) {
725 if (in_array($name, array(
732 $allowStatuses[$val] = $statuses[$val];
736 $allowStatuses = $statuses;
738 $this->add('select', 'contribution_status_id',
739 ts('Payment Status'), $allowStatuses
741 $this->add('text', 'check_number', ts('Check Number'),
742 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
746 //add field for amount to allow an amount to be entered that differs from minimum
747 $this->add('text', 'total_amount', ts('Amount'));
749 $this->add('select', 'financial_type_id',
750 ts('Financial Type'),
751 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType()
754 //CRM-10223 - allow contribution to be recorded against different contact
755 // causes a conflict in standalone mode so skip in standalone for now
756 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
757 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
758 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
760 $this->addElement('checkbox',
762 ts('Send Confirmation and Receipt?'), NULL,
763 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);")
766 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
768 $this->add('textarea', 'receipt_text_signup', ts('Receipt Message'));
770 // Retrieve the name and email of the contact - this will be the TO for receipt email
771 if ($this->_contactID
) {
772 list($this->_memberDisplayName
,
774 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
776 $this->assign('emailExists', $this->_memberEmail
);
777 $this->assign('displayName', $this->_memberDisplayName
);
781 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
782 $recurContributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
,
783 'contribution_recur_id'
785 if ($recurContributionId && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
)) {
787 if (CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
788 $this->assign('cancelAutoRenew',
789 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
792 foreach ($elements as $elem) {
797 $this->assign('isRecur', $isRecur);
799 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
801 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
804 $this->assign('outBound_option', $mailingInfo['outBound_option']);
806 parent
::buildQuickForm();
812 * @param array $params
813 * (ref.) an assoc array of name/value pairs.
818 * @throws CiviCRM_API3_Exception
820 * mixed true or array of errors
822 public static function formRule($params, $files, $self) {
825 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
827 $selectedMemberships = self
::getSelectedMemberships($priceSetId, $params);
830 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
832 $priceFieldIDS = self
::getPriceFieldIDs($params, $self);
834 if (!empty($priceFieldIDS)) {
835 $ids = implode(',', $priceFieldIDS);
837 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
838 foreach ($count as $occurrence) {
839 if ($occurrence > 1) {
840 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
845 elseif (empty($params['membership_type_id'][1])) {
846 $errors['membership_type_id'] = ts('Please select a membership type.');
850 $numterms = CRM_Utils_Array
::value('num_terms', $params);
851 if ($numterms && intval($numterms) != $numterms) {
852 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
856 // Return error if empty $self->_memTypeSelected
857 if ($priceSetId && empty($errors) && empty($selectedMemberships)) {
858 $errors['_qf_default'] = ts('Select at least one membership option.');
861 if (!empty($errors) && (count($selectedMemberships) > 1)) {
862 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($selectedMemberships);
863 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
864 foreach ($duplicateMemberOfContacts as $countDuplicate) {
865 if ($countDuplicate > 1) {
866 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
871 if (!empty($errors)) {
875 if ($priceSetId && !$self->_mode
&& empty($params['record_contribution'])) {
876 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
879 if (!$priceSetId && $self->_mode
&& empty($params['financial_type_id'])) {
880 $errors['financial_type_id'] = ts('Please enter the financial Type.');
883 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
884 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
887 if (!empty($params['is_different_contribution_contact'])) {
888 if (empty($params['soft_credit_type_id'])) {
889 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
891 if (empty($params['soft_credit_contact_id'])) {
892 $errors['soft_credit_contact_id'] = ts('Please select a contact');
896 if (!empty($params['payment_processor_id'])) {
897 // validate payment instrument (e.g. credit card number)
898 CRM_Core_Payment_Form
::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, $self);
902 if (!empty($params['join_date'])) {
904 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
906 foreach ($selectedMemberships as $memType) {
908 if (!empty($params['start_date'])) {
909 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
912 // if end date is set, ensure that start date is also set
913 // and that end date is later than start date
915 if (!empty($params['end_date'])) {
916 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
919 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
921 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) == 'rolling') {
922 if ($startDate < $joinDate) {
923 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
928 if ($membershipDetails['duration_unit'] == 'lifetime') {
929 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
930 // process to update status based on end-date. The user must change the status now.
931 $result = civicrm_api3('MembershipStatus', 'get', array(
933 'is_current_member' => 0,
935 $tmp_statuses = $result['values'];
936 $status_ids = array();
937 foreach ($tmp_statuses as $cur_stat) {
938 $status_ids[] = $cur_stat['id'];
940 if (empty($params['status_id']) ||
in_array($params['status_id'], $status_ids) == FALSE) {
941 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
942 $errors['is_override'] = ts('This must be checked because you set an End Date for a lifetime membership');
947 $errors['start_date'] = ts('Start date must be set if end date is set.');
949 if ($endDate < $startDate) {
950 $errors['end_date'] = ts('End date must be the same or later than start date.');
955 // Default values for start and end dates if not supplied
957 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
964 $startDate = CRM_Utils_Array
::value('start_date',
969 $endDate = CRM_Utils_Array
::value('end_date',
974 //CRM-3724, check for availability of valid membership status.
975 if (empty($params['is_override']) && !isset($errors['_qf_default'])) {
976 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
984 if (empty($calcStatus)) {
985 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
986 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
987 $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));
989 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
991 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
997 $errors['join_date'] = ts('Please enter the Member Since.');
1000 if (isset($params['is_override']) &&
1001 $params['is_override'] && empty($params['status_id'])
1003 $errors['status_id'] = ts('Please enter the status.');
1006 //total amount condition arise when membership type having no
1008 if (isset($params['record_contribution'])) {
1009 if (!$params['financial_type_id']) {
1010 $errors['financial_type_id'] = ts('Please enter the financial Type.');
1012 if (CRM_Utils_System
::isNull($params['total_amount'])) {
1013 $errors['total_amount'] = ts('Please enter the contribution.');
1017 // validate contribution status for 'Failed'.
1018 if ($self->_onlinePendingContributionId
&& !empty($params['record_contribution']) &&
1019 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
1020 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1023 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
1026 return empty($errors) ?
TRUE : $errors;
1030 * Process the form submission.
1032 public function postProcess() {
1033 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1034 CRM_Member_BAO_Membership
::del($this->_id
);
1037 // get the submitted form values.
1038 $this->_params
= $this->controller
->exportValues($this->_name
);
1040 $createdMemberships = $this->submit($this->_params
);
1042 $this->setUserContext();
1046 * Send email receipt.
1048 * @param CRM_Core_Form $form
1050 * @param array $formValues
1051 * @param object $membership
1055 * true if mail was sent successfully
1057 public static function emailReceipt(&$form, &$formValues, &$membership) {
1058 // retrieve 'from email id' for acknowledgement
1059 $receiptFrom = $formValues['from_email_address'];
1061 if (!empty($formValues['payment_instrument_id'])) {
1062 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
1063 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1066 // retrieve custom data
1067 $customFields = $customValues = array();
1068 if (property_exists($form, '_groupTree')
1069 && !empty($form->_groupTree
)
1071 foreach ($form->_groupTree
as $groupID => $group) {
1072 if ($groupID == 'info') {
1075 foreach ($group['fields'] as $k => $field) {
1076 $field['title'] = $field['label'];
1077 $customFields["custom_{$k}"] = $field;
1082 $members = array(array('member_id', '=', $membership->id
, 0, 0));
1083 // check whether its a test drive
1084 if ($form->_mode
== 'test') {
1085 $members[] = array('member_test', '=', 1, 0, 0);
1088 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1092 if (!empty($form->_params
['billing_first_name'])) {
1093 $name = $form->_params
['billing_first_name'];
1096 if (!empty($form->_params
['billing_middle_name'])) {
1097 $name .= " {$form->_params['billing_middle_name']}";
1100 if (!empty($form->_params
['billing_last_name'])) {
1101 $name .= " {$form->_params['billing_last_name']}";
1104 $form->assign('billingName', $name);
1106 // assign the address formatted up for display
1107 $addressParts = array(
1108 "street_address-{$form->_bltID}",
1109 "city-{$form->_bltID}",
1110 "postal_code-{$form->_bltID}",
1111 "state_province-{$form->_bltID}",
1112 "country-{$form->_bltID}",
1114 $addressFields = array();
1115 foreach ($addressParts as $part) {
1116 list($n, $id) = explode('-', $part);
1117 if (isset($form->_params
['billing_' . $part])) {
1118 $addressFields[$n] = $form->_params
['billing_' . $part];
1121 $form->assign('address', CRM_Utils_Address
::format($addressFields));
1123 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
1124 $date = CRM_Utils_Date
::mysqlToIso($date);
1125 $form->assign('credit_card_exp_date', $date);
1126 $form->assign('credit_card_number',
1127 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
1129 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
1130 $form->assign('contributeMode', 'direct');
1131 $form->assign('isAmountzero', 0);
1132 $form->assign('is_pay_later', 0);
1133 $form->assign('isPrimary', 1);
1136 $form->assign('module', 'Membership');
1137 $form->assign('contactID', $formValues['contact_id']);
1139 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
1141 if (!empty($formValues['contribution_id'])) {
1142 $form->assign('contributionID', $formValues['contribution_id']);
1144 elseif (isset($form->_onlinePendingContributionId
)) {
1145 $form->assign('contributionID', $form->_onlinePendingContributionId
);
1148 if (!empty($formValues['contribution_status_id'])) {
1149 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1150 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
1153 if (!empty($formValues['is_renew'])) {
1154 $form->assign('receiptType', 'membership renewal');
1157 $form->assign('receiptType', 'membership signup');
1159 $form->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $formValues)));
1160 $form->assign('formValues', $formValues);
1162 if (empty($lineItem)) {
1163 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1164 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
1165 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1167 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1170 $form->assign('customValues', $customValues);
1171 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1172 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1173 // in this case the form is being called statically from the batch editing screen
1174 // having one class in the form layer call another statically is not greate
1175 // & we should aim to move this function to the BAO layer in future.
1176 // however, we can assume that the contact_id passed in by the batch
1177 // function will be the recipient
1178 list($form->_contributorDisplayName
, $form->_contributorEmail
)
1179 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
1180 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1181 $form->_receiptContactId
= $formValues['contact_id'];
1184 $template = CRM_Core_Smarty
::singleton();
1185 $taxAmt = $template->get_template_vars('dataArray');
1186 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1187 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1188 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1189 if ((!empty($taxAmt) ||
isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1193 $isEmailPdf = FALSE;
1196 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1198 'groupName' => 'msg_tpl_workflow_membership',
1199 'valueName' => 'membership_offline_receipt',
1200 'contactId' => $form->_receiptContactId
,
1201 'from' => $receiptFrom,
1202 'toName' => $form->_contributorDisplayName
,
1203 'toEmail' => $form->_contributorEmail
,
1204 'PDFFilename' => ts('receipt') . '.pdf',
1205 'isEmailPdf' => $isEmailPdf,
1206 'contributionId' => $formValues['contribution_id'],
1207 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
1215 * @param array $formValues
1219 public function submit($formValues) {
1220 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1222 $joinDate = $startDate = $endDate = NULL;
1223 $membershipTypes = $membership = $calcDate = array();
1224 $memType = $membershipType = NULL;
1226 $receiptSend = $mailSend = FALSE;
1227 $priceSetID = CRM_Utils_Array
::value('price_set_id', $formValues);
1229 $params = $softParams = $ids = array();
1231 $allMemberStatus = CRM_Member_PseudoConstant
::membershipStatus();
1232 $allContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
1235 if (!empty($this->_lineItem
)) {
1236 $lineItems = $this->_lineItem
;
1239 // Set variables that we normally get from context.
1240 // In form mode these are set in preProcess.
1241 //TODO: set memberships, fixme
1242 $this->setContextVariables($formValues);
1243 $this->_memTypeSelected
= self
::getSelectedMemberships($priceSetID, $formValues);
1245 $config = CRM_Core_Config
::singleton();
1247 $this->convertDateFieldsToMySQL($formValues);
1249 $membershipTypeValues = array();
1250 foreach ($this->_memTypeSelected
as $memType) {
1251 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1254 //take the required membership recur values.
1255 if ($this->_mode
&& !empty($formValues['auto_renew'])) {
1256 $params['is_recur'] = $this->_params
['is_recur'] = $formValues['is_recur'] = TRUE;
1258 'frequency_interval' => 'duration_interval',
1259 'frequency_unit' => 'duration_unit',
1263 foreach ($this->_memTypeSelected
as $memType) {
1264 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1265 $this->_recurMembershipTypes
, array()
1267 foreach ($mapping as $mapVal => $mapParam) {
1268 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array
::value($mapParam,
1269 $recurMembershipTypeValues
1272 $this->_params
[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1273 $recurMembershipTypeValues
1281 // process price set and get total amount and line items.
1282 $lineItem = array();
1284 CRM_Member_BAO_Membership
::createLineItems($this, $formValues['membership_type_id'], $priceSetID);
1287 if ($priceSetID && CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetID, 'is_quick_config')) {
1291 $termsByType = array();
1293 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1294 $this->_params
, $lineItem[$priceSetID]);
1295 if (CRM_Utils_Array
::value('tax_amount', $this->_params
)) {
1296 $params['tax_amount'] = $this->_params
['tax_amount'];
1298 $params['total_amount'] = CRM_Utils_Array
::value('amount', $this->_params
);
1299 $submittedFinancialType = CRM_Utils_Array
::value('financial_type_id', $formValues);
1300 if (!empty($lineItem[$priceSetId])) {
1301 foreach ($lineItem[$priceSetId] as &$li) {
1302 if (!empty($li['membership_type_id'])) {
1303 if (!empty($li['membership_num_terms'])) {
1304 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1308 ///CRM-11529 for quick config backoffice transactions
1309 //when financial_type_id is passed in form, update the
1310 //lineitems with the financial type selected in form
1311 if ($isQuickConfig && $submittedFinancialType) {
1312 $li['financial_type_id'] = $submittedFinancialType;
1318 $this->storeContactFields($formValues);
1320 $params['contact_id'] = $this->_contactID
;
1329 foreach ($fields as $f) {
1330 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1334 // when is_override false ignore is_admin statuses during membership
1335 // status calculation. similarly we did fix for import in CRM-3570.
1336 if (empty($params['is_override'])) {
1337 $params['exclude_is_admin'] = TRUE;
1340 // process date params to mysql date format.
1342 'join_date' => 'joinDate',
1343 'start_date' => 'startDate',
1344 'end_date' => 'endDate',
1346 foreach ($dateTypes as $dateField => $dateVariable) {
1347 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1350 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1352 $calcDates = array();
1353 foreach ($this->_memTypeSelected
as $memType) {
1354 if (empty($memTypeNumTerms)) {
1355 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1357 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1358 $joinDate, $startDate, $endDate, $memTypeNumTerms
1362 foreach ($calcDates as $memType => $calcDate) {
1363 foreach (array_keys($dateTypes) as $d) {
1364 //first give priority to form values then calDates.
1365 $date = CRM_Utils_Array
::value($d, $formValues);
1367 $date = CRM_Utils_Array
::value($d, $calcDate);
1370 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1371 //$params[$d] = CRM_Utils_Date::processDate( $date );
1375 // max related memberships - take from form or inherit from membership type
1376 foreach ($this->_memTypeSelected
as $memType) {
1377 if (array_key_exists('max_related', $formValues)) {
1378 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array
::value('max_related', $formValues);
1383 $ids['membership'] = $params['id'] = $this->_id
;
1386 $session = CRM_Core_Session
::singleton();
1387 $ids['userId'] = $session->get('userID');
1389 // membership type custom data
1390 foreach ($this->_memTypeSelected
as $memType) {
1391 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE,
1395 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
1396 CRM_Core_BAO_CustomField
::getFields('Membership',
1402 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1408 foreach ($this->_memTypeSelected
as $memType) {
1409 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1414 $membershipType = implode(', ', $membershipTypes);
1416 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1417 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($ids['userId']);
1419 //CRM-13981, allow different person as a soft-contributor of chosen type
1420 if ($this->_contributorContactID
!= $this->_contactID
) {
1421 $params['contribution_contact_id'] = $this->_contributorContactID
;
1422 if (!empty($this->_params
['soft_credit_type_id'])) {
1423 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1424 $softParams['contact_id'] = $this->_contactID
;
1427 if (!empty($formValues['record_contribution'])) {
1428 $recordContribution = array(
1430 'financial_type_id',
1431 'payment_instrument_id',
1433 'contribution_status_id',
1439 foreach ($recordContribution as $f) {
1440 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1443 if (!$this->_onlinePendingContributionId
) {
1444 if (empty($formValues['source'])) {
1445 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(
1446 1 => $membershipType,
1451 $params['contribution_source'] = $formValues['source'];
1455 if (empty($params['is_override']) &&
1456 CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1458 $params['status_id'] = array_search('Pending', $allMemberStatus);
1459 $params['skipStatusCal'] = TRUE;
1460 $params['is_pay_later'] = 1;
1461 $this->assign('is_pay_later', 1);
1464 if (!empty($formValues['send_receipt'])) {
1465 $params['receipt_date'] = CRM_Utils_Array
::value('receive_date', $formValues);
1468 //insert financial type name in receipt.
1469 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1470 $formValues['financial_type_id']
1474 // process line items, until no previous line items.
1475 if (!empty($lineItem)) {
1476 $params['lineItems'] = $lineItem;
1477 $params['processPriceSet'] = TRUE;
1479 $createdMemberships = array();
1481 if (empty($formValues['total_amount']) && !$priceSetId) {
1482 // if total amount not provided minimum for membership type is used
1483 $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1484 $formValues['membership_type_id'][1], 'minimum_fee'
1488 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1491 if ($priceSetId && !$isQuickConfig) {
1492 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1498 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $formValues);
1501 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($formValues['payment_processor_id'],
1505 //get the payment processor id as per mode.
1506 $params['payment_processor_id'] = $this->_params
['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1508 $now = date('YmdHis');
1511 // set email for primary location.
1512 $fields['email-Primary'] = 1;
1513 $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail
;
1514 $params['register_date'] = $now;
1516 // now set the values for the billing location.
1517 foreach ($this->_fields
as $name => $dontCare) {
1521 // also add location name to the array
1522 $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);
1524 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1526 $fields["address_name-{$this->_bltID}"] = 1;
1527 //ensure we don't over-write the payer's email with the member's email
1528 if ($this->_contributorContactID
== $this->_contactID
) {
1529 $fields["email-{$this->_bltID}"] = 1;
1532 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type');
1534 $nameFields = array('first_name', 'middle_name', 'last_name');
1536 foreach ($nameFields as $name) {
1538 if (array_key_exists("billing_$name", $formValues)) {
1539 $formValues[$name] = $formValues["billing_{$name}"];
1540 $formValues['preserveDBName'] = TRUE;
1543 if ($this->_contributorContactID
== $this->_contactID
) {
1544 //see CRM-12869 for discussion of why we don't do this for separate payee payments
1545 CRM_Contact_BAO_Contact
::createProfileContact($formValues, $fields,
1546 $this->_contributorContactID
, NULL, NULL, $ctype
1550 // add all the additional payment params we need
1551 $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}"]);
1552 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1554 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1555 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1556 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1557 $this->_params
['amount'] = $params['total_amount'];
1558 $this->_params
['currencyID'] = $config->defaultCurrency
;
1559 $this->_params
['description'] = ts('Office Credit Card Membership Signup Contribution');
1560 $this->_params
['payment_action'] = 'Sale';
1561 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1562 $this->_params
['financial_type_id'] = $params['financial_type_id'];
1564 // at this point we've created a contact and stored its address etc
1565 // all the payment processors expect the name and address to be in the
1566 // so we copy stuff over to first_name etc.
1567 $paymentParams = $this->_params
;
1568 $paymentParams['contactID'] = $this->_contributorContactID
;
1569 //CRM-10377 if payment is by an alternate contact then we need to set that person
1570 // as the contact in the payment params
1571 if ($this->_contributorContactID
!= $this->_contactID
) {
1572 if (!empty($this->_params
['soft_credit_type_id'])) {
1573 $softParams['contact_id'] = $params['contact_id'];
1574 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1577 if (!empty($this->_params
['send_receipt'])) {
1578 $paymentParams['email'] = $this->_contributorEmail
;
1581 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1583 // CRM-7137 -for recurring membership,
1584 // we do need contribution and recurring records.
1586 if (!empty($paymentParams['is_recur'])) {
1587 $contributionType = new CRM_Financial_DAO_FinancialType();
1588 $contributionType->id
= $params['financial_type_id'];
1589 if (!$contributionType->find(TRUE)) {
1590 CRM_Core_Error
::fatal('Could not find a system table');
1593 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1596 $this->_contributorContactID
,
1605 //create new soft-credit record, CRM-13981
1607 $softParams['contribution_id'] = $contribution->id
;
1608 $softParams['currency'] = $contribution->currency
;
1609 $softParams['amount'] = $contribution->total_amount
;
1610 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1613 $paymentParams['contactID'] = $this->_contactID
;
1614 $paymentParams['contributionID'] = $contribution->id
;
1615 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1616 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1617 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1618 $ids['contribution'] = $contribution->id
;
1619 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1622 if ($params['total_amount'] > 0.0) {
1623 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this);
1624 $result = $payment->doDirectPayment($paymentParams);
1627 if (is_a($result, 'CRM_Core_Error')) {
1628 //make sure to cleanup db for recurring case.
1629 if (!empty($paymentParams['contributionID'])) {
1630 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1632 if (!empty($paymentParams['contributionRecurID'])) {
1633 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1636 CRM_Core_Error
::displaySessionError($result);
1637 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1638 "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
1643 $this->_params
= array_merge($this->_params
, $result);
1644 //assign amount to template if payment was successful
1645 $this->assign('amount', $params['total_amount']);
1648 // if the payment processor returns a contribution_status_id -> use it!
1649 if (isset($result['contribution_status_id'])) {
1650 $params['contribution_status_id'] = $result['contribution_status_id'];
1652 // do what used to happen previously
1654 $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ?
2 : 1;
1656 if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
1657 $params['status_id'] = array_search('Pending', $allMemberStatus);
1658 $params['skipStatusCal'] = TRUE;
1659 // unset send-receipt option, since receipt will be sent when ipn is received.
1660 unset($this->_params
['send_receipt'], $formValues['send_receipt']);
1661 //as membership is pending set dates to null.
1662 $memberDates = array(
1663 'join_date' => 'joinDate',
1664 'start_date' => 'startDate',
1665 'end_date' => 'endDate',
1667 foreach ($memberDates as $dv) {
1669 foreach ($this->_memTypeSelected
as $memType) {
1670 $membershipTypeValues[$memType][$dv] = NULL;
1674 $params['receive_date'] = $now;
1675 $params['invoice_id'] = $this->_params
['invoiceID'];
1676 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1677 array(1 => $membershipType, 2 => $userName)
1679 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1680 $params['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1681 $params['payment_instrument_id'] = 1;
1682 $params['is_test'] = ($this->_mode
== 'live') ?
0 : 1;
1683 if (!empty($this->_params
['send_receipt'])) {
1684 $params['receipt_date'] = $now;
1687 $params['receipt_date'] = NULL;
1690 $this->set('params', $this->_params
);
1691 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1692 $this->assign('receive_date',
1693 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1696 // required for creating membership for related contacts
1697 $params['action'] = $this->_action
;
1699 //create membership record.
1701 foreach ($this->_memTypeSelected
as $memType) {
1703 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1705 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1708 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1710 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1711 $membershipParams['soft_credit'] = $softParams;
1713 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1714 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1715 unset($params['lineItems']);
1716 $this->_membershipIDs
[] = $membership->id
;
1717 $createdMemberships[$memType] = $membership;
1723 $params['action'] = $this->_action
;
1724 if ($this->_onlinePendingContributionId
&& !empty($formValues['record_contribution'])) {
1726 // update membership as well as contribution object, CRM-4395
1727 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1728 $params['componentId'] = $params['id'];
1729 $params['componentName'] = 'contribute';
1730 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1731 if (!empty($result) && !empty($params['contribution_id'])) {
1732 $lineItem = array();
1733 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
1734 $itemId = key($lineItems);
1735 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1737 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1738 $fieldType = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1740 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1741 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1742 $lineItems[$itemId]['id'] = $itemId;
1743 $lineItem[$priceSetId] = $lineItems;
1744 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1745 $contributionBAO->id
= $params['contribution_id'];
1746 $contributionBAO->contact_id
= $params['contact_id'];
1747 $contributionBAO->find();
1748 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1750 //create new soft-credit record, CRM-13981
1752 $softParams['contribution_id'] = $params['contribution_id'];
1753 while ($contributionBAO->fetch()) {
1754 $softParams['currency'] = $contributionBAO->currency
;
1755 $softParams['amount'] = $contributionBAO->total_amount
;
1757 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1761 //carry updated membership object.
1762 $membership = new CRM_Member_DAO_Membership();
1763 $membership->id
= $this->_id
;
1764 $membership->find(TRUE);
1767 if ($membership->end_date
) {
1768 //display end date w/ status message.
1769 $endDate = $membership->end_date
;
1771 if (!in_array($membership->status_id
, array(
1773 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1774 array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus()),
1780 // suppress form values in template.
1781 $this->assign('cancelled', $cancelled);
1783 $createdMemberships[] = $membership;
1787 foreach ($this->_memTypeSelected
as $memType) {
1788 if ($count && !empty($formValues['record_contribution']) &&
1789 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1791 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1794 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1795 if (!empty($formValues['int_amount'])) {
1796 $init_amount = array();
1797 foreach ($formValues as $key => $value) {
1798 if (strstr($key, 'txt-price')) {
1799 $init_amount[$key] = $value;
1802 $membershipParams['init_amount'] = $init_amount;
1805 if (!empty($softParams)) {
1806 $membershipParams['soft_credit'] = $softParams;
1809 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1810 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1811 unset($params['lineItems']);
1813 $this->_membershipIDs
[] = $membership->id
;
1814 $createdMemberships[$memType] = $membership;
1820 if (!empty($lineItem[$priceSetID])) {
1821 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1822 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1824 $totalTaxAmount = 0;
1825 foreach ($lineItem[$priceSetID] as & $priceFieldOp) {
1826 if (!empty($priceFieldOp['membership_type_id'])) {
1827 $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') : '-';
1828 $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') : '-';
1831 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1833 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1835 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1839 $dataArray = array();
1840 foreach ($lineItem[$priceSetID] as $key => $value) {
1841 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1842 if (isset($dataArray[$value['tax_rate']])) {
1843 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1846 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
1851 $this->assign('totalTaxAmount', $totalTaxAmount);
1852 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1854 $this->assign('dataArray', $dataArray);
1857 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1859 $receiptSend = FALSE;
1860 $contributionId = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1861 $membershipIds = $this->_membershipIDs
;
1862 if ($contributionId && !empty($membershipIds)) {
1863 $contributionDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails(
1864 CRM_Export_Form_Select
::MEMBER_EXPORT
, $this->_membershipIDs
);
1865 if ($contributionDetails[$membership->id
]['contribution_status'] == 'Completed') {
1866 $receiptSend = TRUE;
1870 if (!empty($formValues['send_receipt']) && $receiptSend) {
1871 $formValues['contact_id'] = $this->_contactID
;
1872 $formValues['contribution_id'] = $contributionId;
1874 // send email receipt
1875 $mailSend = self
::emailReceipt($this, $formValues, $membership);
1878 // finally set membership id if already not set
1880 $this->_id
= $membership->id
;
1884 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1885 $statusMsg = $this->getStatusMessageForUpdate($membership, $endDate, $receiptSend);
1888 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1889 $statusMsg = $this->getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1890 $params, $calcDates, $mailSend);
1893 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1895 return $createdMemberships;
1898 protected function setUserContext() {
1899 $buttonName = $this->controller
->getButtonName();
1900 $session = CRM_Core_Session
::singleton();
1902 if ($this->_context
== 'standalone') {
1903 if ($buttonName == $this->getButtonName('upload', 'new')) {
1904 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1905 'reset=1&action=add&context=standalone'
1909 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1910 "reset=1&cid={$this->_contactID}&selectedChild=member"
1914 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1915 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1916 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1922 * @param $membership
1924 * @param $receiptSend
1927 protected function getStatusMessageForUpdate($membership, $endDate, $receiptSend) {
1928 //end date can be modified by hooks, so if end date is set then use it.
1929 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1931 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName
));
1932 if ($endDate && $endDate !== 'null') {
1933 $endDate = CRM_Utils_Date
::customFormat($endDate);
1934 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
1938 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1945 * @param $receiptSend
1946 * @param $membershipTypes
1947 * @param $createdMemberships
1951 * @internal param $membership
1952 * @return array|string
1954 protected function getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1955 $params, $calcDates, $mailSent) {
1956 // FIX ME: fix status messages
1958 $statusMsg = array();
1959 foreach ($membershipTypes as $memType => $membershipType) {
1960 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1961 1 => $membershipType,
1962 2 => $this->_memberDisplayName
,
1965 $membership = $createdMemberships[$memType];
1966 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1968 //get the end date from calculated dates.
1969 if (!$memEndDate && empty($params['is_recur'])) {
1970 $memEndDate = CRM_Utils_Array
::value('end_date', $calcDates[$memType]);
1973 if ($memEndDate && $memEndDate !== 'null') {
1974 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1975 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
1978 $statusMsg = implode('<br/>', $statusMsg);
1979 if ($receiptSend && $mailSent) {
1980 $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));