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);
180 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
181 $this->assign('formClass', 'membership');
182 parent
::preProcess();
184 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
185 $this->set('priceSetId', $this->_priceSetId
);
186 $this->assign('priceSetId', $this->_priceSetId
);
188 if ($this->_action
& CRM_Core_Action
::DELETE
) {
189 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
190 // check delete permission for contribution
191 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
192 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."));
196 if ($this->_action
& CRM_Core_Action
::ADD
) {
197 if (!CRM_Member_BAO_Membership
::statusAvailabilty($this->_contactID
)) {
198 // all possible statuses are disabled - redirect back to contact form
199 CRM_Core_Error
::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
202 if ($this->_contactID
) {
203 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
204 $contactMemberships = array();
205 $memParams = array('contact_id' => $this->_contactID
);
206 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
207 $cMemTypes = array();
208 foreach ($contactMemberships as $mem) {
209 $cMemTypes[] = $mem['membership_type_id'];
211 if (count($cMemTypes) > 0) {
212 $memberorgs = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($cMemTypes);
213 $mems_by_org = array();
214 foreach ($contactMemberships as $mem) {
215 $mem['member_of_contact_id'] = CRM_Utils_Array
::value($mem['membership_type_id'], $memberorgs);
216 if (!empty($mem['membership_end_date'])) {
217 $mem['membership_end_date'] = CRM_Utils_Date
::customformat($mem['membership_end_date']);
219 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
220 $mem['membership_type_id'],
223 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
227 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
228 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
229 . ($this->_mode ?
'&mode=live' : '')
231 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
232 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
234 $mems_by_org[$mem['member_of_contact_id']] = $mem;
236 $this->assign('existingContactMemberships', $mems_by_org);
240 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
241 $resources = CRM_Core_Resources
::singleton();
242 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
244 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
245 'memtypes' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'membership_type_id'),
246 'statuses' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'status_id'),
248 $resources->addSetting(array('existingMems' => $passthru));
252 // when custom data is included in this page
253 if (!empty($_POST['hidden_custom'])) {
254 CRM_Custom_Form_CustomData
::preProcess($this);
255 CRM_Custom_Form_CustomData
::buildQuickForm($this);
256 CRM_Custom_Form_CustomData
::setDefaultValues($this);
259 // CRM-4395, get the online pending contribution id.
260 $this->_onlinePendingContributionId
= NULL;
261 if (!$this->_mode
&& $this->_id
&& ($this->_action
& CRM_Core_Action
::UPDATE
)) {
262 $this->_onlinePendingContributionId
= CRM_Contribute_BAO_Contribution
::checkOnlinePendingContribution($this->_id
,
266 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId
);
268 $this->setPageTitle(ts('Membership'));
272 * Set default values for the form. MobileProvider that in edit/view mode
273 * the default values are retrieved from the database
275 public function setDefaultValues() {
276 if ($this->_cdType
) {
277 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
280 if ($this->_priceSetId
) {
281 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
284 $defaults = parent
::setDefaultValues();
286 //setting default join date and receive date
287 list($now, $currentTime) = CRM_Utils_Date
::setDateDefaults();
288 if ($this->_action
== CRM_Core_Action
::ADD
) {
289 $defaults['receive_date'] = $now;
290 $defaults['receive_date_time'] = $currentTime;
293 if (is_numeric($this->_memType
)) {
294 $defaults['membership_type_id'] = array();
295 $defaults['membership_type_id'][0] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
297 'member_of_contact_id',
300 $defaults['membership_type_id'][1] = $this->_memType
;
303 $defaults['membership_type_id'] = $this->_memType
;
306 $defaults['num_terms'] = 1;
308 if (!empty($defaults['id'])) {
309 if ($this->_onlinePendingContributionId
) {
310 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
313 $contributionId = CRM_Core_DAO
::singleValueQuery("
314 SELECT contribution_id
315 FROM civicrm_membership_payment
316 WHERE membership_id = $this->_id
317 ORDER BY contribution_id
320 if ($contributionId) {
321 $defaults['record_contribution'] = $contributionId;
326 //set Soft Credit Type to Gift by default
327 $scTypes = CRM_Core_OptionGroup
::values("soft_credit_type");
328 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
330 if (!empty($defaults['record_contribution']) && !$this->_mode
) {
331 $contributionParams = array('id' => $defaults['record_contribution']);
332 $contributionIds = array();
334 //keep main object campaign in hand.
335 $memberCampaignId = CRM_Utils_Array
::value('campaign_id', $defaults);
337 CRM_Contribute_BAO_Contribution
::getValues($contributionParams, $defaults, $contributionIds);
339 //get back original object campaign id.
340 $defaults['campaign_id'] = $memberCampaignId;
342 if (!empty($defaults['receive_date'])) {
343 list($defaults['receive_date']) = CRM_Utils_Date
::setDateDefaults($defaults['receive_date']);
346 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
347 if (!empty($defaults['membership_source'])) {
348 $defaults['source'] = $defaults['membership_source'];
352 if (empty($defaults['payment_instrument_id'])) {
353 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
356 // User must explicitly choose to send a receipt in both add and update mode.
357 $defaults['send_receipt'] = 0;
359 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
360 // in this mode by default uncheck this checkbox
361 unset($defaults['record_contribution']);
364 $subscriptionCancelled = FALSE;
365 if (!empty($defaults['id'])) {
366 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
369 $alreadyAutoRenew = FALSE;
370 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
371 $defaults['auto_renew'] = 1;
372 $alreadyAutoRenew = TRUE;
374 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
376 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
378 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
380 if (!empty($defaults['is_pay_later'])) {
381 $this->assign('is_pay_later', TRUE);
384 // set default country from config if no country set
385 $config = CRM_Core_Config
::singleton();
386 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
387 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
390 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
391 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
394 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
395 $defaults = array_merge($defaults, $billingDefaults);
397 // // hack to simplify credit card entry for testing
398 // $defaults['credit_card_type'] = 'Visa';
399 // $defaults['credit_card_number'] = '4807731747657838';
400 // $defaults['cvv2'] = '000';
401 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
404 $dates = array('join_date', 'start_date', 'end_date');
405 foreach ($dates as $key) {
406 if (!empty($defaults[$key])) {
407 list($defaults[$key]) = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults));
411 //setting default join date if there is no join date
412 if (empty($defaults['join_date'])) {
413 $defaults['join_date'] = $now;
416 if (!empty($defaults['membership_end_date'])) {
417 $this->assign('endDate', $defaults['membership_end_date']);
424 * Build the form object.
426 public function buildQuickForm() {
427 if ($this->_cdType
) {
428 return CRM_Custom_Form_CustomData
::buildQuickForm($this);
431 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
433 $this->assign('currency', CRM_Core_Config
::singleton()->defaultCurrencySymbol
);
434 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
435 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
436 if (isset($invoicing)) {
437 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
439 // build price set form.
440 $buildPriceSet = FALSE;
441 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
442 if (!empty($_POST['price_set_id'])) {
443 $buildPriceSet = TRUE;
445 $getOnlyPriceSetElements = TRUE;
446 if (!$this->_priceSetId
) {
447 $this->_priceSetId
= $_POST['price_set_id'];
448 $getOnlyPriceSetElements = FALSE;
451 $this->set('priceSetId', $this->_priceSetId
);
452 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
454 $optionsMembershipTypes = array();
455 foreach ($this->_priceSet
['fields'] as $pField) {
456 if (empty($pField['options'])) {
459 foreach ($pField['options'] as $opId => $opValues) {
460 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
464 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
466 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
467 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
469 // get only price set form elements.
470 if ($getOnlyPriceSetElements) {
475 // use to build form during form rule.
476 $this->assign('buildPriceSet', $buildPriceSet);
478 if ($this->_action
& CRM_Core_Action
::ADD
) {
479 $buildPriceSet = FALSE;
480 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
481 if (!empty($priceSets)) {
482 $buildPriceSet = TRUE;
485 if ($buildPriceSet) {
486 $this->add('select', 'price_set_id', ts('Choose price set'),
488 '' => ts('Choose price set'),
490 NULL, array('onchange' => "buildAmount( this.value );")
493 $this->assign('hasPriceSets', $buildPriceSet);
496 //need to assign custom data type and subtype to the template
497 $this->assign('customDataType', 'Membership');
498 $this->assign('customDataSubType', $this->_memType
);
499 $this->assign('entityID', $this->_id
);
501 if ($this->_action
& CRM_Core_Action
::DELETE
) {
502 $this->addButtons(array(
505 'name' => ts('Delete'),
506 'spacing' => ' ',
511 'name' => ts('Cancel'),
518 if ($this->_context
== 'standalone') {
519 $this->addEntityRef('contact_id', ts('Contact'), array(
521 'api' => array('extra' => array('email')),
525 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
527 $dao = new CRM_Member_DAO_MembershipType();
528 $dao->domain_id
= CRM_Core_Config
::domainID();
531 // retrieve all memberships
532 $allMemberships = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this);
534 $allMembershipInfo = $membershipType = array();
535 foreach ($allMemberships as $key => $values) {
536 if (!empty($values['is_active'])) {
537 $membershipType[$key] = CRM_Utils_Array
::value('name', $values);
538 if ($this->_mode
&& empty($values['minimum_fee'])) {
542 $memberOfContactId = CRM_Utils_Array
::value('member_of_contact_id', $values);
543 if (empty($selMemTypeOrg[$memberOfContactId])) {
544 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
550 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
552 if (empty($selOrgMemType[$memberOfContactId][$key])) {
553 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array
::value('name', $values);
557 // build membership info array, which is used when membership type is selected to:
558 // - set the payment information block
559 // - set the max related block
560 $allMembershipInfo[$key] = array(
561 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $values),
562 'total_amount' => CRM_Utils_Money
::format($values['minimum_fee'], NULL, '%a'),
563 'total_amount_numeric' => CRM_Utils_Array
::value('minimum_fee', $values),
564 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $values),
565 'has_related' => isset($values['relationship_type_id']),
566 'max_related' => CRM_Utils_Array
::value('max_related', $values),
571 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
573 // show organization by default, if only one organization in
575 if (count($selMemTypeOrg) == 2) {
576 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
578 //sort membership organization and type, CRM-6099
579 natcasesort($selMemTypeOrg);
580 foreach ($selOrgMemType as $index => $orgMembershipType) {
581 natcasesort($orgMembershipType);
582 $selOrgMemType[$index] = $orgMembershipType;
585 $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
587 //build the form for auto renew.
588 $autoRenew = array();
589 if ($this->_mode ||
($this->_action
& CRM_Core_Action
::UPDATE
)) {
590 $this->addElement('checkbox',
592 ts('Membership renewed automatically'),
594 array('onclick' => "buildReceiptANDNotice( );")
598 //get the valid recurring processors.
599 $test = strtolower($this->_mode
) == 'test' ?
TRUE : FALSE;
600 $recurring = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, $test, 'is_recur = 1');
601 $recurProcessor = array_intersect_key($this->_processors
, $recurring);
602 $autoRenew = array();
603 if (!empty($recurProcessor)) {
604 if (!empty($membershipType)) {
610 FROM civicrm_membership_type
611 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
612 $recurMembershipTypes = CRM_Core_DAO
::executeQuery($sql);
613 while ($recurMembershipTypes->fetch()) {
614 $autoRenew[$recurMembershipTypes->id
] = $recurMembershipTypes->auto_renew
;
621 $this->_recurMembershipTypes
[$recurMembershipTypes->id
][$fld] = $recurMembershipTypes->$fld;
627 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
632 $allowAutoRenew = FALSE;
633 if ($this->_mode
&& !empty($recurProcessor)) {
634 $allowAutoRenew = TRUE;
636 $this->assign('allowAutoRenew', $allowAutoRenew);
637 $this->assign('autoRenewOptions', json_encode($autoRenew));
638 $this->assign('recurProcessor', json_encode($recurProcessor));
640 // for max_related: a little JS to show/hide & set default value
641 $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
642 $this->add('text', 'max_related', ts('Max related'),
643 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
646 $sel = &$this->addElement('hierselect',
647 'membership_type_id',
648 ts('Membership Organization and Type'),
652 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
658 $this->applyFilter('__ALL__', 'trim');
660 if ($this->_action
& CRM_Core_Action
::ADD
) {
661 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
664 $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
665 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
666 $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
668 $elements[] = $endDate;
671 $this->add('text', 'source', ts('Source'),
672 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
675 //CRM-7362 --add campaigns.
678 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
680 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
683 $this->add('select', 'status_id', ts('Membership Status'),
684 array('' => ts('- select -')) + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
686 $statusOverride = $this->addElement('checkbox', 'is_override',
687 ts('Status Override?'), NULL,
688 array('onClick' => 'showHideMemberStatus()')
690 if ($statusOverride) {
691 $elements[] = $statusOverride;
694 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
696 $this->add('text', 'total_amount', ts('Amount'));
697 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
699 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
701 $this->add('select', 'payment_instrument_id',
703 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
704 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
706 $this->add('text', 'trxn_id', ts('Transaction ID'));
707 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
708 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id
, 'trxn_id')
711 $allowStatuses = array();
712 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
713 if ($this->_onlinePendingContributionId
) {
714 $statusNames = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
715 foreach ($statusNames as $val => $name) {
716 if (in_array($name, array(
723 $allowStatuses[$val] = $statuses[$val];
727 $allowStatuses = $statuses;
729 $this->add('select', 'contribution_status_id',
730 ts('Payment Status'), $allowStatuses
732 $this->add('text', 'check_number', ts('Check Number'),
733 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
737 //add field for amount to allow an amount to be entered that differs from minimum
738 $this->add('text', 'total_amount', ts('Amount'));
740 $this->add('select', 'financial_type_id',
741 ts('Financial Type'),
742 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType()
745 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
747 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
748 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
750 $this->addElement('checkbox',
752 ts('Send Confirmation and Receipt?'), NULL,
753 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);")
756 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
758 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
760 // Retrieve the name and email of the contact - this will be the TO for receipt email
761 if ($this->_contactID
) {
762 list($this->_memberDisplayName
,
764 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
766 $this->assign('emailExists', $this->_memberEmail
);
767 $this->assign('displayName', $this->_memberDisplayName
);
771 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
772 $recurContributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
,
773 'contribution_recur_id'
775 if ($recurContributionId && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
)) {
777 if (CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
778 $this->assign('cancelAutoRenew',
779 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
782 foreach ($elements as $elem) {
787 $this->assign('isRecur', $isRecur);
789 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
791 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
794 $this->assign('outBound_option', $mailingInfo['outBound_option']);
796 parent
::buildQuickForm();
802 * @param array $params
803 * (ref.) an assoc array of name/value pairs.
808 * @throws CiviCRM_API3_Exception
810 * mixed true or array of errors
812 public static function formRule($params, $files, $self) {
815 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
817 $selectedMemberships = self
::getSelectedMemberships($priceSetId, $params);
820 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
822 $priceFieldIDS = self
::getPriceFieldIDs($params, $self);
824 if (!empty($priceFieldIDS)) {
825 $ids = implode(',', $priceFieldIDS);
827 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
828 foreach ($count as $occurrence) {
829 if ($occurrence > 1) {
830 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
835 elseif (empty($params['membership_type_id'][1])) {
836 $errors['membership_type_id'] = ts('Please select a membership type.');
840 $numterms = CRM_Utils_Array
::value('num_terms', $params);
841 if ($numterms && intval($numterms) != $numterms) {
842 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
846 // Return error if empty $self->_memTypeSelected
847 if ($priceSetId && empty($errors) && empty($selectedMemberships)) {
848 $errors['_qf_default'] = ts('Select at least one membership option.');
851 if (!empty($errors) && (count($selectedMemberships) > 1)) {
852 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($selectedMemberships);
853 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
854 foreach ($duplicateMemberOfContacts as $countDuplicate) {
855 if ($countDuplicate > 1) {
856 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
861 if (!empty($errors)) {
865 if ($priceSetId && !$self->_mode
&& empty($params['record_contribution'])) {
866 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
869 if (!$priceSetId && $self->_mode
&& empty($params['financial_type_id'])) {
870 $errors['financial_type_id'] = ts('Please enter the financial Type.');
873 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
874 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
877 if (!empty($params['is_different_contribution_contact'])) {
878 if (empty($params['soft_credit_type_id'])) {
879 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
881 if (empty($params['soft_credit_contact_id'])) {
882 $errors['soft_credit_contact_id'] = ts('Please select a contact');
886 if (!empty($params['payment_processor_id'])) {
887 // validate payment instrument (e.g. credit card number)
888 CRM_Core_Payment_Form
::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, $self);
892 if (!empty($params['join_date'])) {
894 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
896 foreach ($selectedMemberships as $memType) {
898 if (!empty($params['start_date'])) {
899 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
902 // if end date is set, ensure that start date is also set
903 // and that end date is later than start date
905 if (!empty($params['end_date'])) {
906 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
909 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
911 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) == 'rolling') {
912 if ($startDate < $joinDate) {
913 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
918 if ($membershipDetails['duration_unit'] == 'lifetime') {
919 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
920 // process to update status based on end-date. The user must change the status now.
921 $result = civicrm_api3('MembershipStatus', 'get', array(
923 'is_current_member' => 0,
925 $tmp_statuses = $result['values'];
926 $status_ids = array();
927 foreach ($tmp_statuses as $cur_stat) {
928 $status_ids[] = $cur_stat['id'];
930 if (empty($params['status_id']) ||
in_array($params['status_id'], $status_ids) == FALSE) {
931 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
932 $errors['is_override'] = ts('This must be checked because you set an End Date for a lifetime membership');
937 $errors['start_date'] = ts('Start date must be set if end date is set.');
939 if ($endDate < $startDate) {
940 $errors['end_date'] = ts('End date must be the same or later than start date.');
945 // Default values for start and end dates if not supplied
947 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
954 $startDate = CRM_Utils_Array
::value('start_date',
959 $endDate = CRM_Utils_Array
::value('end_date',
964 //CRM-3724, check for availability of valid membership status.
965 if (empty($params['is_override']) && !isset($errors['_qf_default'])) {
966 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
974 if (empty($calcStatus)) {
975 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
976 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
977 $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));
979 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
981 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
987 $errors['join_date'] = ts('Please enter the Member Since.');
990 if (isset($params['is_override']) &&
991 $params['is_override'] && empty($params['status_id'])
993 $errors['status_id'] = ts('Please enter the status.');
996 //total amount condition arise when membership type having no
998 if (isset($params['record_contribution'])) {
999 if (!$params['financial_type_id']) {
1000 $errors['financial_type_id'] = ts('Please enter the financial Type.');
1002 if (CRM_Utils_System
::isNull($params['total_amount'])) {
1003 $errors['total_amount'] = ts('Please enter the contribution.');
1007 // validate contribution status for 'Failed'.
1008 if ($self->_onlinePendingContributionId
&& !empty($params['record_contribution']) &&
1009 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
1010 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1013 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
1016 return empty($errors) ?
TRUE : $errors;
1020 * Process the form submission.
1022 public function postProcess() {
1023 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1024 CRM_Member_BAO_Membership
::del($this->_id
);
1027 // get the submitted form values.
1028 $this->_params
= $this->controller
->exportValues($this->_name
);
1030 $this->submit($this->_params
);
1032 $this->setUserContext();
1036 * Send email receipt.
1038 * @param CRM_Core_Form $form
1040 * @param array $formValues
1041 * @param object $membership
1045 * true if mail was sent successfully
1047 public static function emailReceipt(&$form, &$formValues, &$membership) {
1048 // retrieve 'from email id' for acknowledgement
1049 $receiptFrom = $formValues['from_email_address'];
1051 if (!empty($formValues['payment_instrument_id'])) {
1052 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
1053 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1056 // retrieve custom data
1057 $customFields = $customValues = array();
1058 if (property_exists($form, '_groupTree')
1059 && !empty($form->_groupTree
)
1061 foreach ($form->_groupTree
as $groupID => $group) {
1062 if ($groupID == 'info') {
1065 foreach ($group['fields'] as $k => $field) {
1066 $field['title'] = $field['label'];
1067 $customFields["custom_{$k}"] = $field;
1072 $members = array(array('member_id', '=', $membership->id
, 0, 0));
1073 // check whether its a test drive
1074 if ($form->_mode
== 'test') {
1075 $members[] = array('member_test', '=', 1, 0, 0);
1078 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1082 if (!empty($form->_params
['billing_first_name'])) {
1083 $name = $form->_params
['billing_first_name'];
1086 if (!empty($form->_params
['billing_middle_name'])) {
1087 $name .= " {$form->_params['billing_middle_name']}";
1090 if (!empty($form->_params
['billing_last_name'])) {
1091 $name .= " {$form->_params['billing_last_name']}";
1094 $form->assign('billingName', $name);
1096 // assign the address formatted up for display
1097 $addressParts = array(
1098 "street_address-{$form->_bltID}",
1099 "city-{$form->_bltID}",
1100 "postal_code-{$form->_bltID}",
1101 "state_province-{$form->_bltID}",
1102 "country-{$form->_bltID}",
1104 $addressFields = array();
1105 foreach ($addressParts as $part) {
1106 list($n, $id) = explode('-', $part);
1107 if (isset($form->_params
['billing_' . $part])) {
1108 $addressFields[$n] = $form->_params
['billing_' . $part];
1111 $form->assign('address', CRM_Utils_Address
::format($addressFields));
1113 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
1114 $date = CRM_Utils_Date
::mysqlToIso($date);
1115 $form->assign('credit_card_exp_date', $date);
1116 $form->assign('credit_card_number',
1117 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
1119 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
1120 $form->assign('contributeMode', 'direct');
1121 $form->assign('isAmountzero', 0);
1122 $form->assign('is_pay_later', 0);
1123 $form->assign('isPrimary', 1);
1126 $form->assign('module', 'Membership');
1127 $form->assign('contactID', $formValues['contact_id']);
1129 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
1131 if (!empty($formValues['contribution_id'])) {
1132 $form->assign('contributionID', $formValues['contribution_id']);
1134 elseif (isset($form->_onlinePendingContributionId
)) {
1135 $form->assign('contributionID', $form->_onlinePendingContributionId
);
1138 if (!empty($formValues['contribution_status_id'])) {
1139 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1140 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
1143 if (!empty($formValues['is_renew'])) {
1144 $form->assign('receiptType', 'membership renewal');
1147 $form->assign('receiptType', 'membership signup');
1149 $form->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $formValues)));
1150 $form->assign('formValues', $formValues);
1152 if (empty($lineItem)) {
1153 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1154 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
1155 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1157 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1160 $form->assign('customValues', $customValues);
1161 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1162 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1163 // in this case the form is being called statically from the batch editing screen
1164 // having one class in the form layer call another statically is not greate
1165 // & we should aim to move this function to the BAO layer in future.
1166 // however, we can assume that the contact_id passed in by the batch
1167 // function will be the recipient
1168 list($form->_contributorDisplayName
, $form->_contributorEmail
)
1169 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
1170 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1171 $form->_receiptContactId
= $formValues['contact_id'];
1174 $template = CRM_Core_Smarty
::singleton();
1175 $taxAmt = $template->get_template_vars('dataArray');
1176 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1177 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1178 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1179 if ((!empty($taxAmt) ||
isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1183 $isEmailPdf = FALSE;
1186 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1188 'groupName' => 'msg_tpl_workflow_membership',
1189 'valueName' => 'membership_offline_receipt',
1190 'contactId' => $form->_receiptContactId
,
1191 'from' => $receiptFrom,
1192 'toName' => $form->_contributorDisplayName
,
1193 'toEmail' => $form->_contributorEmail
,
1194 'PDFFilename' => ts('receipt') . '.pdf',
1195 'isEmailPdf' => $isEmailPdf,
1196 'contributionId' => $formValues['contribution_id'],
1197 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
1205 * @param array $formValues
1209 public function submit($formValues) {
1210 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1212 $joinDate = $startDate = $endDate = NULL;
1213 $membershipTypes = $membership = $calcDate = array();
1214 $membershipType = NULL;
1217 $priceSetID = CRM_Utils_Array
::value('price_set_id', $formValues);
1219 $params = $softParams = $ids = array();
1221 $allMemberStatus = CRM_Member_PseudoConstant
::membershipStatus();
1222 $allContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
1225 if (!empty($this->_lineItem
)) {
1226 $lineItems = $this->_lineItem
;
1229 // Set variables that we normally get from context.
1230 // In form mode these are set in preProcess.
1231 //TODO: set memberships, fixme
1232 $this->setContextVariables($formValues);
1233 $this->_memTypeSelected
= self
::getSelectedMemberships($priceSetID, $formValues);
1235 $config = CRM_Core_Config
::singleton();
1237 $this->convertDateFieldsToMySQL($formValues);
1239 $membershipTypeValues = array();
1240 foreach ($this->_memTypeSelected
as $memType) {
1241 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1244 //take the required membership recur values.
1245 if ($this->_mode
&& !empty($formValues['auto_renew'])) {
1246 $params['is_recur'] = $this->_params
['is_recur'] = $formValues['is_recur'] = TRUE;
1248 'frequency_interval' => 'duration_interval',
1249 'frequency_unit' => 'duration_unit',
1253 foreach ($this->_memTypeSelected
as $memType) {
1254 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1255 $this->_recurMembershipTypes
, array()
1257 foreach ($mapping as $mapVal => $mapParam) {
1258 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array
::value($mapParam,
1259 $recurMembershipTypeValues
1262 $this->_params
[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1263 $recurMembershipTypeValues
1271 // process price set and get total amount and line items.
1272 $lineItem = array();
1274 CRM_Member_BAO_Membership
::createLineItems($this, $formValues['membership_type_id'], $priceSetID);
1277 if ($priceSetID && CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetID, 'is_quick_config')) {
1281 $termsByType = array();
1283 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1284 $this->_params
, $lineItem[$priceSetID]);
1285 if (CRM_Utils_Array
::value('tax_amount', $this->_params
)) {
1286 $params['tax_amount'] = $this->_params
['tax_amount'];
1288 $params['total_amount'] = CRM_Utils_Array
::value('amount', $this->_params
);
1289 $submittedFinancialType = CRM_Utils_Array
::value('financial_type_id', $formValues);
1290 if (!empty($lineItem[$priceSetID])) {
1291 foreach ($lineItem[$priceSetID] as &$li) {
1292 if (!empty($li['membership_type_id'])) {
1293 if (!empty($li['membership_num_terms'])) {
1294 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1298 ///CRM-11529 for quick config backoffice transactions
1299 //when financial_type_id is passed in form, update the
1300 //lineitems with the financial type selected in form
1301 if ($isQuickConfig && $submittedFinancialType) {
1302 $li['financial_type_id'] = $submittedFinancialType;
1308 $this->storeContactFields($formValues);
1310 $params['contact_id'] = $this->_contactID
;
1319 foreach ($fields as $f) {
1320 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1324 // when is_override false ignore is_admin statuses during membership
1325 // status calculation. similarly we did fix for import in CRM-3570.
1326 if (empty($params['is_override'])) {
1327 $params['exclude_is_admin'] = TRUE;
1330 // process date params to mysql date format.
1332 'join_date' => 'joinDate',
1333 'start_date' => 'startDate',
1334 'end_date' => 'endDate',
1336 foreach ($dateTypes as $dateField => $dateVariable) {
1337 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1340 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1342 $calcDates = array();
1343 foreach ($this->_memTypeSelected
as $memType) {
1344 if (empty($memTypeNumTerms)) {
1345 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1347 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1348 $joinDate, $startDate, $endDate, $memTypeNumTerms
1352 foreach ($calcDates as $memType => $calcDate) {
1353 foreach (array_keys($dateTypes) as $d) {
1354 //first give priority to form values then calDates.
1355 $date = CRM_Utils_Array
::value($d, $formValues);
1357 $date = CRM_Utils_Array
::value($d, $calcDate);
1360 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1361 //$params[$d] = CRM_Utils_Date::processDate( $date );
1365 // max related memberships - take from form or inherit from membership type
1366 foreach ($this->_memTypeSelected
as $memType) {
1367 if (array_key_exists('max_related', $formValues)) {
1368 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array
::value('max_related', $formValues);
1373 $ids['membership'] = $params['id'] = $this->_id
;
1376 $session = CRM_Core_Session
::singleton();
1377 $ids['userId'] = $session->get('userID');
1379 // membership type custom data
1380 foreach ($this->_memTypeSelected
as $memType) {
1381 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1387 foreach ($this->_memTypeSelected
as $memType) {
1388 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1393 $membershipType = implode(', ', $membershipTypes);
1395 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1396 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($ids['userId']);
1398 //CRM-13981, allow different person as a soft-contributor of chosen type
1399 if ($this->_contributorContactID
!= $this->_contactID
) {
1400 $params['contribution_contact_id'] = $this->_contributorContactID
;
1401 if (!empty($this->_params
['soft_credit_type_id'])) {
1402 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1403 $softParams['contact_id'] = $this->_contactID
;
1406 if (!empty($formValues['record_contribution'])) {
1407 $recordContribution = array(
1409 'financial_type_id',
1410 'payment_instrument_id',
1412 'contribution_status_id',
1418 foreach ($recordContribution as $f) {
1419 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1422 if (!$this->_onlinePendingContributionId
) {
1423 if (empty($formValues['source'])) {
1424 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(
1425 1 => $membershipType,
1430 $params['contribution_source'] = $formValues['source'];
1434 if (empty($params['is_override']) &&
1435 CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
1437 $params['status_id'] = array_search('Pending', $allMemberStatus);
1438 $params['skipStatusCal'] = TRUE;
1439 $params['is_pay_later'] = 1;
1440 $this->assign('is_pay_later', 1);
1443 if (!empty($formValues['send_receipt'])) {
1444 $params['receipt_date'] = CRM_Utils_Array
::value('receive_date', $formValues);
1447 //insert financial type name in receipt.
1448 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1449 $formValues['financial_type_id']
1453 // process line items, until no previous line items.
1454 if (!empty($lineItem)) {
1455 $params['lineItems'] = $lineItem;
1456 $params['processPriceSet'] = TRUE;
1458 $createdMemberships = array();
1460 if (empty($formValues['total_amount']) && !$priceSetID) {
1461 // if total amount not provided minimum for membership type is used
1462 $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1463 $formValues['membership_type_id'][1], 'minimum_fee'
1467 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1470 if ($priceSetID && !$isQuickConfig) {
1471 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1477 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $formValues);
1480 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($formValues['payment_processor_id'],
1484 //get the payment processor id as per mode.
1485 $params['payment_processor_id'] = $this->_params
['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1487 $now = date('YmdHis');
1490 // set email for primary location.
1491 $fields['email-Primary'] = 1;
1492 $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail
;
1493 $params['register_date'] = $now;
1495 // now set the values for the billing location.
1496 foreach ($this->_fields
as $name => $dontCare) {
1500 // also add location name to the array
1501 $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);
1503 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1505 $fields["address_name-{$this->_bltID}"] = 1;
1506 //ensure we don't over-write the payer's email with the member's email
1507 if ($this->_contributorContactID
== $this->_contactID
) {
1508 $fields["email-{$this->_bltID}"] = 1;
1511 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID
, 'contact_type');
1513 $nameFields = array('first_name', 'middle_name', 'last_name');
1515 foreach ($nameFields as $name) {
1517 if (array_key_exists("billing_$name", $formValues)) {
1518 $formValues[$name] = $formValues["billing_{$name}"];
1519 $formValues['preserveDBName'] = TRUE;
1522 if ($this->_contributorContactID
== $this->_contactID
) {
1523 //see CRM-12869 for discussion of why we don't do this for separate payee payments
1524 CRM_Contact_BAO_Contact
::createProfileContact($formValues, $fields,
1525 $this->_contributorContactID
, NULL, NULL, $ctype
1529 // add all the additional payment params we need
1530 $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}"]);
1531 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1533 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1534 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1535 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1536 $this->_params
['amount'] = $params['total_amount'];
1537 $this->_params
['currencyID'] = $config->defaultCurrency
;
1538 $this->_params
['description'] = ts('Office Credit Card Membership Signup Contribution');
1539 $this->_params
['payment_action'] = 'Sale';
1540 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1541 $this->_params
['financial_type_id'] = $params['financial_type_id'];
1543 // at this point we've created a contact and stored its address etc
1544 // all the payment processors expect the name and address to be in the
1545 // so we copy stuff over to first_name etc.
1546 $paymentParams = $this->_params
;
1547 $paymentParams['contactID'] = $this->_contributorContactID
;
1548 //CRM-10377 if payment is by an alternate contact then we need to set that person
1549 // as the contact in the payment params
1550 if ($this->_contributorContactID
!= $this->_contactID
) {
1551 if (!empty($this->_params
['soft_credit_type_id'])) {
1552 $softParams['contact_id'] = $params['contact_id'];
1553 $softParams['soft_credit_type_id'] = $this->_params
['soft_credit_type_id'];
1556 if (!empty($this->_params
['send_receipt'])) {
1557 $paymentParams['email'] = $this->_contributorEmail
;
1560 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1562 // CRM-7137 -for recurring membership,
1563 // we do need contribution and recurring records.
1565 if (!empty($paymentParams['is_recur'])) {
1566 $contributionType = new CRM_Financial_DAO_FinancialType();
1567 $contributionType->id
= $params['financial_type_id'];
1568 if (!$contributionType->find(TRUE)) {
1569 CRM_Core_Error
::fatal('Could not find a system table');
1572 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1575 $this->_contributorContactID
,
1584 //create new soft-credit record, CRM-13981
1586 $softParams['contribution_id'] = $contribution->id
;
1587 $softParams['currency'] = $contribution->currency
;
1588 $softParams['amount'] = $contribution->total_amount
;
1589 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1592 $paymentParams['contactID'] = $this->_contactID
;
1593 $paymentParams['contributionID'] = $contribution->id
;
1594 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1595 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1596 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1597 $ids['contribution'] = $contribution->id
;
1598 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1601 if ($params['total_amount'] > 0.0) {
1602 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this);
1603 $result = $payment->doDirectPayment($paymentParams);
1606 if (is_a($result, 'CRM_Core_Error')) {
1607 //make sure to cleanup db for recurring case.
1608 if (!empty($paymentParams['contributionID'])) {
1609 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1611 if (!empty($paymentParams['contributionRecurID'])) {
1612 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1615 CRM_Core_Error
::displaySessionError($result);
1616 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1617 "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
1622 $this->_params
= array_merge($this->_params
, $result);
1623 //assign amount to template if payment was successful
1624 $this->assign('amount', $params['total_amount']);
1627 // if the payment processor returns a contribution_status_id -> use it!
1628 if (isset($result['contribution_status_id'])) {
1629 $params['contribution_status_id'] = $result['contribution_status_id'];
1631 // do what used to happen previously
1633 $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ?
2 : 1;
1635 if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
1636 $params['status_id'] = array_search('Pending', $allMemberStatus);
1637 $params['skipStatusCal'] = TRUE;
1638 // unset send-receipt option, since receipt will be sent when ipn is received.
1639 unset($this->_params
['send_receipt'], $formValues['send_receipt']);
1640 //as membership is pending set dates to null.
1641 $memberDates = array(
1642 'join_date' => 'joinDate',
1643 'start_date' => 'startDate',
1644 'end_date' => 'endDate',
1646 foreach ($memberDates as $dv) {
1648 foreach ($this->_memTypeSelected
as $memType) {
1649 $membershipTypeValues[$memType][$dv] = NULL;
1653 $params['receive_date'] = $now;
1654 $params['invoice_id'] = $this->_params
['invoiceID'];
1655 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1656 array(1 => $membershipType, 2 => $userName)
1658 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1659 $params['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1660 $params['payment_instrument_id'] = 1;
1661 $params['is_test'] = ($this->_mode
== 'live') ?
0 : 1;
1662 if (!empty($this->_params
['send_receipt'])) {
1663 $params['receipt_date'] = $now;
1666 $params['receipt_date'] = NULL;
1669 $this->set('params', $this->_params
);
1670 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1671 $this->assign('receive_date',
1672 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1675 // required for creating membership for related contacts
1676 $params['action'] = $this->_action
;
1678 //create membership record.
1680 foreach ($this->_memTypeSelected
as $memType) {
1682 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1684 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1687 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1689 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1690 $membershipParams['soft_credit'] = $softParams;
1692 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1693 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1694 unset($params['lineItems']);
1695 $this->_membershipIDs
[] = $membership->id
;
1696 $createdMemberships[$memType] = $membership;
1702 $params['action'] = $this->_action
;
1703 if ($this->_onlinePendingContributionId
&& !empty($formValues['record_contribution'])) {
1705 // update membership as well as contribution object, CRM-4395
1706 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1707 $params['componentId'] = $params['id'];
1708 $params['componentName'] = 'contribute';
1709 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1710 if (!empty($result) && !empty($params['contribution_id'])) {
1711 $lineItem = array();
1712 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
1713 $itemId = key($lineItems);
1714 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1716 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1717 $fieldType = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1719 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1720 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1721 $lineItems[$itemId]['id'] = $itemId;
1722 $lineItem[$priceSetId] = $lineItems;
1723 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1724 $contributionBAO->id
= $params['contribution_id'];
1725 $contributionBAO->contact_id
= $params['contact_id'];
1726 $contributionBAO->find();
1727 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1729 //create new soft-credit record, CRM-13981
1731 $softParams['contribution_id'] = $params['contribution_id'];
1732 while ($contributionBAO->fetch()) {
1733 $softParams['currency'] = $contributionBAO->currency
;
1734 $softParams['amount'] = $contributionBAO->total_amount
;
1736 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1740 //carry updated membership object.
1741 $membership = new CRM_Member_DAO_Membership();
1742 $membership->id
= $this->_id
;
1743 $membership->find(TRUE);
1746 if ($membership->end_date
) {
1747 //display end date w/ status message.
1748 $endDate = $membership->end_date
;
1750 if (!in_array($membership->status_id
, array(
1752 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1753 array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus()),
1759 // suppress form values in template.
1760 $this->assign('cancelled', $cancelled);
1762 $createdMemberships[] = $membership;
1766 foreach ($this->_memTypeSelected
as $memType) {
1767 if ($count && !empty($formValues['record_contribution']) &&
1768 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1770 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1773 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1774 if (!empty($formValues['int_amount'])) {
1775 $init_amount = array();
1776 foreach ($formValues as $key => $value) {
1777 if (strstr($key, 'txt-price')) {
1778 $init_amount[$key] = $value;
1781 $membershipParams['init_amount'] = $init_amount;
1784 if (!empty($softParams)) {
1785 $membershipParams['soft_credit'] = $softParams;
1788 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1789 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1790 unset($params['lineItems']);
1792 $this->_membershipIDs
[] = $membership->id
;
1793 $createdMemberships[$memType] = $membership;
1799 if (!empty($lineItem[$priceSetID])) {
1800 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1801 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1803 $totalTaxAmount = 0;
1804 foreach ($lineItem[$priceSetID] as & $priceFieldOp) {
1805 if (!empty($priceFieldOp['membership_type_id'])) {
1806 $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') : '-';
1807 $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') : '-';
1810 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1812 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1814 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1818 $dataArray = array();
1819 foreach ($lineItem[$priceSetID] as $key => $value) {
1820 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1821 if (isset($dataArray[$value['tax_rate']])) {
1822 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1825 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
1830 $this->assign('totalTaxAmount', $totalTaxAmount);
1831 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1833 $this->assign('dataArray', $dataArray);
1836 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1838 $receiptSend = FALSE;
1839 $contributionId = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1840 $membershipIds = $this->_membershipIDs
;
1841 if ($contributionId && !empty($membershipIds)) {
1842 $contributionDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails(
1843 CRM_Export_Form_Select
::MEMBER_EXPORT
, $this->_membershipIDs
);
1844 if ($contributionDetails[$membership->id
]['contribution_status'] == 'Completed') {
1845 $receiptSend = TRUE;
1849 if (!empty($formValues['send_receipt']) && $receiptSend) {
1850 $formValues['contact_id'] = $this->_contactID
;
1851 $formValues['contribution_id'] = $contributionId;
1852 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1853 // handled in the receipt. But by setting one we avoid breaking templates for now
1854 // although at some point we should switch in the templates.
1855 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1856 // send email receipt
1857 $mailSend = self
::emailReceipt($this, $formValues, $membership);
1860 // finally set membership id if already not set
1862 $this->_id
= $membership->id
;
1866 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1867 $statusMsg = $this->getStatusMessageForUpdate($membership, $endDate, $receiptSend);
1870 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1871 $statusMsg = $this->getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1872 $params, $calcDates, $mailSend);
1875 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1877 return $createdMemberships;
1880 protected function setUserContext() {
1881 $buttonName = $this->controller
->getButtonName();
1882 $session = CRM_Core_Session
::singleton();
1884 if ($this->_context
== 'standalone') {
1885 if ($buttonName == $this->getButtonName('upload', 'new')) {
1886 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1887 'reset=1&action=add&context=standalone'
1891 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1892 "reset=1&cid={$this->_contactID}&selectedChild=member"
1896 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1897 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1898 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1904 * @param $membership
1906 * @param $receiptSend
1909 protected function getStatusMessageForUpdate($membership, $endDate, $receiptSend) {
1910 //end date can be modified by hooks, so if end date is set then use it.
1911 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1913 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName
));
1914 if ($endDate && $endDate !== 'null') {
1915 $endDate = CRM_Utils_Date
::customFormat($endDate);
1916 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
1920 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));
1927 * @param $receiptSend
1928 * @param $membershipTypes
1929 * @param $createdMemberships
1933 * @internal param $membership
1934 * @return array|string
1936 protected function getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1937 $params, $calcDates, $mailSent) {
1938 // FIX ME: fix status messages
1940 $statusMsg = array();
1941 foreach ($membershipTypes as $memType => $membershipType) {
1942 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1943 1 => $membershipType,
1944 2 => $this->_memberDisplayName
,
1947 $membership = $createdMemberships[$memType];
1948 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1950 //get the end date from calculated dates.
1951 if (!$memEndDate && empty($params['is_recur'])) {
1952 $memEndDate = CRM_Utils_Array
::value('end_date', $calcDates[$memType]);
1955 if ($memEndDate && $memEndDate !== 'null') {
1956 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1957 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
1960 $statusMsg = implode('<br/>', $statusMsg);
1961 if ($receiptSend && $mailSent) {
1962 $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail
));