Use function on parent class to assign processors rather than duplication
[civicrm-core.git] / CRM / Member / Form / Membership.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for offline membership form
38 *
39 */
40 class CRM_Member_Form_Membership extends CRM_Member_Form {
41
42 protected $_memType = NULL;
43
44 protected $_onlinePendingContributionId;
45
46 public $_mode;
47
48 public $_contributeMode = 'direct';
49
50 protected $_recurMembershipTypes;
51
52 protected $_memTypeSelected;
53
54 /**
55 * Display name of the member.
56 *
57 * @var string
58 */
59 protected $_memberDisplayName = NULL;
60
61 /**
62 * email of the person paying for the membership (used for receipts)
63 */
64 protected $_memberEmail = NULL;
65
66 /**
67 * Contact ID of the member.
68 *
69 * @var int
70 */
71 public $_contactID = NULL;
72
73 /**
74 * Display name of the person paying for the membership (used for receipts)
75 *
76 * @var string
77 */
78 protected $_contributorDisplayName = NULL;
79
80 /**
81 * email of the person paying for the membership (used for receipts)
82 */
83 protected $_contributorEmail = NULL;
84
85 /**
86 * email of the person paying for the membership (used for receipts)
87 *
88 * @var int
89 */
90 protected $_contributorContactID = NULL;
91
92 /**
93 * ID of the person the receipt is to go to.
94 *
95 * @var int
96 */
97 protected $_receiptContactId = NULL;
98
99 /**
100 * Keep a class variable for ALL membeshipID's so
101 * postProcess hook function can do something with it
102 *
103 * @var array
104 */
105 protected $_membershipIDs = array();
106
107 /**
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
110 *
111 * @var array
112 */
113 protected $_dateFields = array(
114 'receive_date' => array('default' => 'now'),
115 );
116
117 /**
118 * Get selected membership type from the form values.
119 *
120 * @param int $priceSetID
121 * @param array $params
122 *
123 * @return array
124 */
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;
132 }
133 }
134 }
135 else {
136 $memTypeSelected = $params['membership_type_id'];
137 }
138 return $memTypeSelected;
139 }
140
141 /**
142 * Extract price set fields and values from $params.
143 *
144 * @param $params
145 * @return array
146 */
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']);
153 }
154 }
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) {
159 if ($isSet) {
160 $priceFieldIDS[] = $priceFldVal;
161 }
162 }
163 }
164 else {
165 $priceFieldIDS[] = $params['price_' . $fieldId];
166 }
167 }
168 }
169 return $priceFieldIDS;
170 }
171
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);
179 }
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();
183 // get price set id.
184 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
185 $this->set('priceSetId', $this->_priceSetId);
186 $this->assign('priceSetId', $this->_priceSetId);
187
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."));
193 }
194 }
195
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'));
200 }
201
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'];
210 }
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']);
218 }
219 $mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
220 $mem['membership_type_id'],
221 'name', 'id'
222 );
223 $mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
224 $mem['status_id'],
225 'label', 'id'
226 );
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' : '')
230 );
231 $mem['membershipTab'] = CRM_Utils_System::url('civicrm/contact/view',
232 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
233 );
234 $mems_by_org[$mem['member_of_contact_id']] = $mem;
235 }
236 $this->assign('existingContactMemberships', $mems_by_org);
237 }
238 }
239 else {
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');
243 $passthru = array(
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'),
247 );
248 $resources->addSetting(array('existingMems' => $passthru));
249 }
250 }
251
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);
257 }
258
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,
263 'Membership'
264 );
265 }
266 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId);
267
268 $this->setPageTitle(ts('Membership'));
269 }
270
271 /**
272 * Set default values for the form. MobileProvider that in edit/view mode
273 * the default values are retrieved from the database
274 */
275 public function setDefaultValues() {
276 if ($this->_cdType) {
277 return CRM_Custom_Form_CustomData::setDefaultValues($this);
278 }
279
280 if ($this->_priceSetId) {
281 return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
282 }
283
284 $defaults = parent::setDefaultValues();
285
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;
291 }
292
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',
296 $this->_memType,
297 'member_of_contact_id',
298 'id'
299 );
300 $defaults['membership_type_id'][1] = $this->_memType;
301 }
302 else {
303 $defaults['membership_type_id'] = $this->_memType;
304 }
305
306 $defaults['num_terms'] = 1;
307
308 if (!empty($defaults['id'])) {
309 if ($this->_onlinePendingContributionId) {
310 $defaults['record_contribution'] = $this->_onlinePendingContributionId;
311 }
312 else {
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
318 DESC limit 1");
319
320 if ($contributionId) {
321 $defaults['record_contribution'] = $contributionId;
322 }
323 }
324 }
325
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));
329
330 if (!empty($defaults['record_contribution']) && !$this->_mode) {
331 $contributionParams = array('id' => $defaults['record_contribution']);
332 $contributionIds = array();
333
334 //keep main object campaign in hand.
335 $memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults);
336
337 CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
338
339 //get back original object campaign id.
340 $defaults['campaign_id'] = $memberCampaignId;
341
342 if (!empty($defaults['receive_date'])) {
343 list($defaults['receive_date']) = CRM_Utils_Date::setDateDefaults($defaults['receive_date']);
344 }
345
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'];
349 }
350 }
351 //CRM-13420
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'));
354 }
355
356 // User must explicitly choose to send a receipt in both add and update mode.
357 $defaults['send_receipt'] = 0;
358
359 if ($this->_action & CRM_Core_Action::UPDATE) {
360 // in this mode by default uncheck this checkbox
361 unset($defaults['record_contribution']);
362 }
363
364 $subscriptionCancelled = FALSE;
365 if (!empty($defaults['id'])) {
366 $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
367 }
368
369 $alreadyAutoRenew = FALSE;
370 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
371 $defaults['auto_renew'] = 1;
372 $alreadyAutoRenew = TRUE;
373 }
374 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
375
376 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
377
378 $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults));
379
380 if (!empty($defaults['is_pay_later'])) {
381 $this->assign('is_pay_later', TRUE);
382 }
383 if ($this->_mode) {
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;
388 }
389
390 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
391 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
392 }
393
394 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
395 $defaults = array_merge($defaults, $billingDefaults);
396
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' );
402 }
403
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));
408 }
409 }
410
411 //setting default join date if there is no join date
412 if (empty($defaults['join_date'])) {
413 $defaults['join_date'] = $now;
414 }
415
416 if (!empty($defaults['membership_end_date'])) {
417 $this->assign('endDate', $defaults['membership_end_date']);
418 }
419
420 return $defaults;
421 }
422
423 /**
424 * Build the form object.
425 */
426 public function buildQuickForm() {
427 if ($this->_cdType) {
428 return CRM_Custom_Form_CustomData::buildQuickForm($this);
429 }
430
431 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
432
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));
438 }
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;
444 }
445 $getOnlyPriceSetElements = TRUE;
446 if (!$this->_priceSetId) {
447 $this->_priceSetId = $_POST['price_set_id'];
448 $getOnlyPriceSetElements = FALSE;
449 }
450
451 $this->set('priceSetId', $this->_priceSetId);
452 CRM_Price_BAO_PriceSet::buildPriceSet($this);
453
454 $optionsMembershipTypes = array();
455 foreach ($this->_priceSet['fields'] as $pField) {
456 if (empty($pField['options'])) {
457 continue;
458 }
459 foreach ($pField['options'] as $opId => $opValues) {
460 $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
461 }
462 }
463
464 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
465
466 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
467 $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
468
469 // get only price set form elements.
470 if ($getOnlyPriceSetElements) {
471 return;
472 }
473 }
474
475 // use to build form during form rule.
476 $this->assign('buildPriceSet', $buildPriceSet);
477
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;
483 }
484
485 if ($buildPriceSet) {
486 $this->add('select', 'price_set_id', ts('Choose price set'),
487 array(
488 '' => ts('Choose price set'),
489 ) + $priceSets,
490 NULL, array('onchange' => "buildAmount( this.value );")
491 );
492 }
493 $this->assign('hasPriceSets', $buildPriceSet);
494 }
495
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);
500
501 if ($this->_action & CRM_Core_Action::DELETE) {
502 $this->addButtons(array(
503 array(
504 'type' => 'next',
505 'name' => ts('Delete'),
506 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
507 'isDefault' => TRUE,
508 ),
509 array(
510 'type' => 'cancel',
511 'name' => ts('Cancel'),
512 ),
513 )
514 );
515 return;
516 }
517
518 if ($this->_context == 'standalone') {
519 $this->addEntityRef('contact_id', ts('Contact'), array(
520 'create' => TRUE,
521 'api' => array('extra' => array('email')),
522 ), TRUE);
523 }
524
525 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
526
527 $dao = new CRM_Member_DAO_MembershipType();
528 $dao->domain_id = CRM_Core_Config::domainID();
529 $dao->find();
530
531 // retrieve all memberships
532 $allMemberships = CRM_Member_BAO_Membership::buildMembershipTypeValues($this);
533
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'])) {
539 continue;
540 }
541 else {
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',
545 $memberOfContactId,
546 'display_name',
547 'id'
548 );
549
550 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
551 }
552 if (empty($selOrgMemType[$memberOfContactId][$key])) {
553 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
554 }
555 }
556
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),
567 );
568 }
569 }
570
571 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
572
573 // show organization by default, if only one organization in
574 // the list
575 if (count($selMemTypeOrg) == 2) {
576 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
577 }
578 //sort membership organization and type, CRM-6099
579 natcasesort($selMemTypeOrg);
580 foreach ($selOrgMemType as $index => $orgMembershipType) {
581 natcasesort($orgMembershipType);
582 $selOrgMemType[$index] = $orgMembershipType;
583 }
584
585 $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
586
587 //build the form for auto renew.
588 $autoRenew = array();
589 if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
590 $this->addElement('checkbox',
591 'auto_renew',
592 ts('Membership renewed automatically'),
593 NULL,
594 array('onclick' => "buildReceiptANDNotice( );")
595 );
596
597 $this->assignPaymentRelatedVariables();
598
599 if ($this->_mode) {
600 if (!empty($this->_recurPaymentProcessors)) {
601 if (!empty($membershipType)) {
602 $sql = '
603 SELECT id,
604 auto_renew,
605 duration_unit,
606 duration_interval
607 FROM civicrm_membership_type
608 WHERE id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
609 $recurMembershipTypes = CRM_Core_DAO::executeQuery($sql);
610 while ($recurMembershipTypes->fetch()) {
611 $autoRenew[$recurMembershipTypes->id] = $recurMembershipTypes->auto_renew;
612 foreach (array(
613 'id',
614 'auto_renew',
615 'duration_unit',
616 'duration_interval',
617 ) as $fld) {
618 $this->_recurMembershipTypes[$recurMembershipTypes->id][$fld] = $recurMembershipTypes->$fld;
619 }
620 }
621 }
622 $memTypeJs = array(
623 'onChange' =>
624 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
625 );
626 $this->assign('allowAutoRenew', TRUE);
627 }
628 }
629 }
630
631 $this->assign('autoRenewOptions', json_encode($autoRenew));
632
633 // for max_related: a little JS to show/hide & set default value
634 $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
635 $this->add('text', 'max_related', ts('Max related'),
636 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related')
637 );
638
639 $sel = &$this->addElement('hierselect',
640 'membership_type_id',
641 ts('Membership Organization and Type'),
642 $memTypeJs
643 );
644
645 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
646 $elements = array();
647 if ($sel) {
648 $elements[] = $sel;
649 }
650
651 $this->applyFilter('__ALL__', 'trim');
652
653 if ($this->_action & CRM_Core_Action::ADD) {
654 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
655 }
656
657 $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
658 $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
659 $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
660 if ($endDate) {
661 $elements[] = $endDate;
662 }
663
664 $this->add('text', 'source', ts('Source'),
665 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source')
666 );
667
668 //CRM-7362 --add campaigns.
669 $campaignId = NULL;
670 if ($this->_id) {
671 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
672 }
673 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
674
675 if (!$this->_mode) {
676 $this->add('select', 'status_id', ts('Membership Status'),
677 array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
678 );
679 $statusOverride = $this->addElement('checkbox', 'is_override',
680 ts('Status Override?'), NULL,
681 array('onClick' => 'showHideMemberStatus()')
682 );
683 if ($statusOverride) {
684 $elements[] = $statusOverride;
685 }
686
687 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
688
689 $this->add('text', 'total_amount', ts('Amount'));
690 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
691
692 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
693
694 $this->add('select', 'payment_instrument_id',
695 ts('Paid By'),
696 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
697 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
698 );
699 $this->add('text', 'trxn_id', ts('Transaction ID'));
700 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
701 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')
702 );
703
704 $allowStatuses = array();
705 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
706 if ($this->_onlinePendingContributionId) {
707 $statusNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
708 foreach ($statusNames as $val => $name) {
709 if (in_array($name, array(
710 'In Progress',
711 'Overdue',
712 ))
713 ) {
714 continue;
715 }
716 $allowStatuses[$val] = $statuses[$val];
717 }
718 }
719 else {
720 $allowStatuses = $statuses;
721 }
722 $this->add('select', 'contribution_status_id',
723 ts('Payment Status'), $allowStatuses
724 );
725 $this->add('text', 'check_number', ts('Check Number'),
726 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
727 );
728 }
729 else {
730 //add field for amount to allow an amount to be entered that differs from minimum
731 $this->add('text', 'total_amount', ts('Amount'));
732 }
733 $this->add('select', 'financial_type_id',
734 ts('Financial Type'),
735 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
736 );
737
738 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
739
740 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
741 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
742
743 $this->addElement('checkbox',
744 'send_receipt',
745 ts('Send Confirmation and Receipt?'), NULL,
746 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);")
747 );
748
749 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
750
751 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
752
753 // Retrieve the name and email of the contact - this will be the TO for receipt email
754 if ($this->_contactID) {
755 list($this->_memberDisplayName,
756 $this->_memberEmail
757 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
758
759 $this->assign('emailExists', $this->_memberEmail);
760 $this->assign('displayName', $this->_memberDisplayName);
761 }
762
763 $isRecur = FALSE;
764 if ($this->_action & CRM_Core_Action::UPDATE) {
765 $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id,
766 'contribution_recur_id'
767 );
768 if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
769 $isRecur = TRUE;
770 if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
771 $this->assign('cancelAutoRenew',
772 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
773 );
774 }
775 foreach ($elements as $elem) {
776 $elem->freeze();
777 }
778 }
779 }
780 $this->assign('isRecur', $isRecur);
781
782 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
783
784 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
785 'mailing_backend'
786 );
787 $this->assign('outBound_option', $mailingInfo['outBound_option']);
788
789 parent::buildQuickForm();
790 }
791
792 /**
793 * Validation.
794 *
795 * @param array $params
796 * (ref.) an assoc array of name/value pairs.
797 *
798 * @param $files
799 * @param $self
800 *
801 * @throws CiviCRM_API3_Exception
802 * @return bool|array
803 * mixed true or array of errors
804 */
805 public static function formRule($params, $files, $self) {
806 $errors = array();
807
808 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
809
810 $selectedMemberships = self::getSelectedMemberships($priceSetId, $params);
811
812 if ($priceSetId) {
813 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
814
815 $priceFieldIDS = self::getPriceFieldIDs($params, $self);
816
817 if (!empty($priceFieldIDS)) {
818 $ids = implode(',', $priceFieldIDS);
819
820 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
821 foreach ($count as $occurrence) {
822 if ($occurrence > 1) {
823 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
824 }
825 }
826 }
827 }
828 elseif (empty($params['membership_type_id'][1])) {
829 $errors['membership_type_id'] = ts('Please select a membership type.');
830 }
831
832 if (!$priceSetId) {
833 $numterms = CRM_Utils_Array::value('num_terms', $params);
834 if ($numterms && intval($numterms) != $numterms) {
835 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
836 }
837 }
838
839 // Return error if empty $self->_memTypeSelected
840 if ($priceSetId && empty($errors) && empty($selectedMemberships)) {
841 $errors['_qf_default'] = ts('Select at least one membership option.');
842 }
843
844 if (!empty($errors) && (count($selectedMemberships) > 1)) {
845 $memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
846 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
847 foreach ($duplicateMemberOfContacts as $countDuplicate) {
848 if ($countDuplicate > 1) {
849 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
850 }
851 }
852 }
853
854 if (!empty($errors)) {
855 return $errors;
856 }
857
858 if ($priceSetId && !$self->_mode && empty($params['record_contribution'])) {
859 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
860 }
861
862 if (!$priceSetId && $self->_mode && empty($params['financial_type_id'])) {
863 $errors['financial_type_id'] = ts('Please enter the financial Type.');
864 }
865
866 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
867 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
868 }
869
870 if (!empty($params['is_different_contribution_contact'])) {
871 if (empty($params['soft_credit_type_id'])) {
872 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
873 }
874 if (empty($params['soft_credit_contact_id'])) {
875 $errors['soft_credit_contact_id'] = ts('Please select a contact');
876 }
877 }
878
879 if (!empty($params['payment_processor_id'])) {
880 // validate payment instrument (e.g. credit card number)
881 CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, $self);
882 }
883
884 $joinDate = NULL;
885 if (!empty($params['join_date'])) {
886
887 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
888
889 foreach ($selectedMemberships as $memType) {
890 $startDate = NULL;
891 if (!empty($params['start_date'])) {
892 $startDate = CRM_Utils_Date::processDate($params['start_date']);
893 }
894
895 // if end date is set, ensure that start date is also set
896 // and that end date is later than start date
897 $endDate = NULL;
898 if (!empty($params['end_date'])) {
899 $endDate = CRM_Utils_Date::processDate($params['end_date']);
900 }
901
902 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($memType);
903
904 if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) == 'rolling') {
905 if ($startDate < $joinDate) {
906 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
907 }
908 }
909
910 if ($endDate) {
911 if ($membershipDetails['duration_unit'] == 'lifetime') {
912 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
913 // process to update status based on end-date. The user must change the status now.
914 $result = civicrm_api3('MembershipStatus', 'get', array(
915 'sequential' => 1,
916 'is_current_member' => 0,
917 ));
918 $tmp_statuses = $result['values'];
919 $status_ids = array();
920 foreach ($tmp_statuses as $cur_stat) {
921 $status_ids[] = $cur_stat['id'];
922 }
923 if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
924 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
925 $errors['is_override'] = ts('This must be checked because you set an End Date for a lifetime membership');
926 }
927 }
928 else {
929 if (!$startDate) {
930 $errors['start_date'] = ts('Start date must be set if end date is set.');
931 }
932 if ($endDate < $startDate) {
933 $errors['end_date'] = ts('End date must be the same or later than start date.');
934 }
935 }
936 }
937
938 // Default values for start and end dates if not supplied
939 // on the form
940 $defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
941 $joinDate,
942 $startDate,
943 $endDate
944 );
945
946 if (!$startDate) {
947 $startDate = CRM_Utils_Array::value('start_date',
948 $defaultDates
949 );
950 }
951 if (!$endDate) {
952 $endDate = CRM_Utils_Array::value('end_date',
953 $defaultDates
954 );
955 }
956
957 //CRM-3724, check for availability of valid membership status.
958 if (empty($params['is_override']) && !isset($errors['_qf_default'])) {
959 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
960 $endDate,
961 $joinDate,
962 'today',
963 TRUE,
964 $memType,
965 $params
966 );
967 if (empty($calcStatus)) {
968 $url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
969 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
970 $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));
971 if (!$self->_mode) {
972 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
973 }
974 CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
975 }
976 }
977 }
978 }
979 else {
980 $errors['join_date'] = ts('Please enter the Member Since.');
981 }
982
983 if (isset($params['is_override']) &&
984 $params['is_override'] && empty($params['status_id'])
985 ) {
986 $errors['status_id'] = ts('Please enter the status.');
987 }
988
989 //total amount condition arise when membership type having no
990 //minimum fee
991 if (isset($params['record_contribution'])) {
992 if (!$params['financial_type_id']) {
993 $errors['financial_type_id'] = ts('Please enter the financial Type.');
994 }
995 if (CRM_Utils_System::isNull($params['total_amount'])) {
996 $errors['total_amount'] = ts('Please enter the contribution.');
997 }
998 }
999
1000 // validate contribution status for 'Failed'.
1001 if ($self->_onlinePendingContributionId && !empty($params['record_contribution']) &&
1002 (CRM_Utils_Array::value('contribution_status_id', $params) ==
1003 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
1004 )
1005 ) {
1006 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
1007 }
1008
1009 return empty($errors) ? TRUE : $errors;
1010 }
1011
1012 /**
1013 * Process the form submission.
1014 */
1015 public function postProcess() {
1016 if ($this->_action & CRM_Core_Action::DELETE) {
1017 CRM_Member_BAO_Membership::del($this->_id);
1018 return;
1019 }
1020 // get the submitted form values.
1021 $this->_params = $this->controller->exportValues($this->_name);
1022
1023 $this->submit($this->_params);
1024
1025 $this->setUserContext();
1026 }
1027
1028 /**
1029 * Send email receipt.
1030 *
1031 * @param CRM_Core_Form $form
1032 * Form object.
1033 * @param array $formValues
1034 * @param object $membership
1035 * Object.
1036 *
1037 * @return bool
1038 * true if mail was sent successfully
1039 */
1040 public static function emailReceipt(&$form, &$formValues, &$membership) {
1041 // retrieve 'from email id' for acknowledgement
1042 $receiptFrom = $formValues['from_email_address'];
1043
1044 if (!empty($formValues['payment_instrument_id'])) {
1045 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1046 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1047 }
1048
1049 // retrieve custom data
1050 $customFields = $customValues = array();
1051 if (property_exists($form, '_groupTree')
1052 && !empty($form->_groupTree)
1053 ) {
1054 foreach ($form->_groupTree as $groupID => $group) {
1055 if ($groupID == 'info') {
1056 continue;
1057 }
1058 foreach ($group['fields'] as $k => $field) {
1059 $field['title'] = $field['label'];
1060 $customFields["custom_{$k}"] = $field;
1061 }
1062 }
1063 }
1064
1065 $members = array(array('member_id', '=', $membership->id, 0, 0));
1066 // check whether its a test drive
1067 if ($form->_mode == 'test') {
1068 $members[] = array('member_test', '=', 1, 0, 0);
1069 }
1070
1071 CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1072
1073 if ($form->_mode) {
1074 $name = '';
1075 if (!empty($form->_params['billing_first_name'])) {
1076 $name = $form->_params['billing_first_name'];
1077 }
1078
1079 if (!empty($form->_params['billing_middle_name'])) {
1080 $name .= " {$form->_params['billing_middle_name']}";
1081 }
1082
1083 if (!empty($form->_params['billing_last_name'])) {
1084 $name .= " {$form->_params['billing_last_name']}";
1085 }
1086
1087 $form->assign('billingName', $name);
1088
1089 // assign the address formatted up for display
1090 $addressParts = array(
1091 "street_address-{$form->_bltID}",
1092 "city-{$form->_bltID}",
1093 "postal_code-{$form->_bltID}",
1094 "state_province-{$form->_bltID}",
1095 "country-{$form->_bltID}",
1096 );
1097 $addressFields = array();
1098 foreach ($addressParts as $part) {
1099 list($n, $id) = explode('-', $part);
1100 if (isset($form->_params['billing_' . $part])) {
1101 $addressFields[$n] = $form->_params['billing_' . $part];
1102 }
1103 }
1104 $form->assign('address', CRM_Utils_Address::format($addressFields));
1105
1106 $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']);
1107 $date = CRM_Utils_Date::mysqlToIso($date);
1108 $form->assign('credit_card_exp_date', $date);
1109 $form->assign('credit_card_number',
1110 CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])
1111 );
1112 $form->assign('credit_card_type', $form->_params['credit_card_type']);
1113 $form->assign('contributeMode', 'direct');
1114 $form->assign('isAmountzero', 0);
1115 $form->assign('is_pay_later', 0);
1116 $form->assign('isPrimary', 1);
1117 }
1118
1119 $form->assign('module', 'Membership');
1120 $form->assign('contactID', $formValues['contact_id']);
1121
1122 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
1123
1124 if (!empty($formValues['contribution_id'])) {
1125 $form->assign('contributionID', $formValues['contribution_id']);
1126 }
1127 elseif (isset($form->_onlinePendingContributionId)) {
1128 $form->assign('contributionID', $form->_onlinePendingContributionId);
1129 }
1130
1131 if (!empty($formValues['contribution_status_id'])) {
1132 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1133 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
1134 }
1135
1136 if (!empty($formValues['is_renew'])) {
1137 $form->assign('receiptType', 'membership renewal');
1138 }
1139 else {
1140 $form->assign('receiptType', 'membership signup');
1141 }
1142 $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues)));
1143 $form->assign('formValues', $formValues);
1144
1145 if (empty($lineItem)) {
1146 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y'));
1147 if (!CRM_Utils_System::isNull($membership->end_date)) {
1148 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y'));
1149 }
1150 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
1151 }
1152
1153 $form->assign('customValues', $customValues);
1154 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1155 if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail)) || $isBatchProcess) {
1156 // in this case the form is being called statically from the batch editing screen
1157 // having one class in the form layer call another statically is not greate
1158 // & we should aim to move this function to the BAO layer in future.
1159 // however, we can assume that the contact_id passed in by the batch
1160 // function will be the recipient
1161 list($form->_contributorDisplayName, $form->_contributorEmail)
1162 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
1163 if (empty($form->_receiptContactId) || $isBatchProcess) {
1164 $form->_receiptContactId = $formValues['contact_id'];
1165 }
1166 }
1167 $template = CRM_Core_Smarty::singleton();
1168 $taxAmt = $template->get_template_vars('dataArray');
1169 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1170 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1171 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1172 if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1173 $isEmailPdf = TRUE;
1174 }
1175 else {
1176 $isEmailPdf = FALSE;
1177 }
1178
1179 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1180 array(
1181 'groupName' => 'msg_tpl_workflow_membership',
1182 'valueName' => 'membership_offline_receipt',
1183 'contactId' => $form->_receiptContactId,
1184 'from' => $receiptFrom,
1185 'toName' => $form->_contributorDisplayName,
1186 'toEmail' => $form->_contributorEmail,
1187 'PDFFilename' => ts('receipt') . '.pdf',
1188 'isEmailPdf' => $isEmailPdf,
1189 'contributionId' => $formValues['contribution_id'],
1190 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
1191 )
1192 );
1193
1194 return TRUE;
1195 }
1196
1197 /**
1198 * @param array $formValues
1199
1200 * @return array
1201 */
1202 public function submit($formValues) {
1203 $isTest = ($this->_mode == 'test') ? 1 : 0;
1204
1205 $joinDate = $startDate = $endDate = NULL;
1206 $membershipTypes = $membership = $calcDate = array();
1207 $membershipType = NULL;
1208
1209 $mailSend = FALSE;
1210 $priceSetID = CRM_Utils_Array::value('price_set_id', $formValues);
1211
1212 $params = $softParams = $ids = array();
1213
1214 $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
1215 $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
1216
1217 $lineItems = NULL;
1218 if (!empty($this->_lineItem)) {
1219 $lineItems = $this->_lineItem;
1220 }
1221
1222 // Set variables that we normally get from context.
1223 // In form mode these are set in preProcess.
1224 //TODO: set memberships, fixme
1225 $this->setContextVariables($formValues);
1226 $this->_memTypeSelected = self::getSelectedMemberships($priceSetID, $formValues);
1227
1228 $config = CRM_Core_Config::singleton();
1229
1230 $this->convertDateFieldsToMySQL($formValues);
1231
1232 $membershipTypeValues = array();
1233 foreach ($this->_memTypeSelected as $memType) {
1234 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1235 }
1236
1237 //take the required membership recur values.
1238 if ($this->_mode && !empty($formValues['auto_renew'])) {
1239 $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
1240 $mapping = array(
1241 'frequency_interval' => 'duration_interval',
1242 'frequency_unit' => 'duration_unit',
1243 );
1244
1245 $count = 0;
1246 foreach ($this->_memTypeSelected as $memType) {
1247 $recurMembershipTypeValues = CRM_Utils_Array::value($memType,
1248 $this->_recurMembershipTypes, array()
1249 );
1250 foreach ($mapping as $mapVal => $mapParam) {
1251 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam,
1252 $recurMembershipTypeValues
1253 );
1254 if (!$count) {
1255 $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam,
1256 $recurMembershipTypeValues
1257 );
1258 }
1259 }
1260 $count++;
1261 }
1262 }
1263
1264 // process price set and get total amount and line items.
1265 $lineItem = array();
1266 if ($priceSetID) {
1267 CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetID);
1268 }
1269 $isQuickConfig = 0;
1270 if ($priceSetID && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetID, 'is_quick_config')) {
1271 $isQuickConfig = 1;
1272 }
1273
1274 $termsByType = array();
1275 if ($priceSetID) {
1276 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1277 $this->_params, $lineItem[$priceSetID]);
1278 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1279 $params['tax_amount'] = $this->_params['tax_amount'];
1280 }
1281 $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
1282 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
1283 if (!empty($lineItem[$priceSetID])) {
1284 foreach ($lineItem[$priceSetID] as &$li) {
1285 if (!empty($li['membership_type_id'])) {
1286 if (!empty($li['membership_num_terms'])) {
1287 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1288 }
1289 }
1290
1291 ///CRM-11529 for quick config backoffice transactions
1292 //when financial_type_id is passed in form, update the
1293 //lineitems with the financial type selected in form
1294 if ($isQuickConfig && $submittedFinancialType) {
1295 $li['financial_type_id'] = $submittedFinancialType;
1296 }
1297 }
1298 }
1299 }
1300
1301 $this->storeContactFields($formValues);
1302
1303 $params['contact_id'] = $this->_contactID;
1304
1305 $fields = array(
1306 'status_id',
1307 'source',
1308 'is_override',
1309 'campaign_id',
1310 );
1311
1312 foreach ($fields as $f) {
1313 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1314 }
1315
1316 // fix for CRM-3724
1317 // when is_override false ignore is_admin statuses during membership
1318 // status calculation. similarly we did fix for import in CRM-3570.
1319 if (empty($params['is_override'])) {
1320 $params['exclude_is_admin'] = TRUE;
1321 }
1322
1323 // process date params to mysql date format.
1324 $dateTypes = array(
1325 'join_date' => 'joinDate',
1326 'start_date' => 'startDate',
1327 'end_date' => 'endDate',
1328 );
1329 foreach ($dateTypes as $dateField => $dateVariable) {
1330 $$dateVariable = CRM_Utils_Date::processDate($formValues[$dateField]);
1331 }
1332
1333 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
1334
1335 $calcDates = array();
1336 foreach ($this->_memTypeSelected as $memType) {
1337 if (empty($memTypeNumTerms)) {
1338 $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
1339 }
1340 $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
1341 $joinDate, $startDate, $endDate, $memTypeNumTerms
1342 );
1343 }
1344
1345 foreach ($calcDates as $memType => $calcDate) {
1346 foreach (array_keys($dateTypes) as $d) {
1347 //first give priority to form values then calDates.
1348 $date = CRM_Utils_Array::value($d, $formValues);
1349 if (!$date) {
1350 $date = CRM_Utils_Array::value($d, $calcDate);
1351 }
1352
1353 $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
1354 //$params[$d] = CRM_Utils_Date::processDate( $date );
1355 }
1356 }
1357
1358 // max related memberships - take from form or inherit from membership type
1359 foreach ($this->_memTypeSelected as $memType) {
1360 if (array_key_exists('max_related', $formValues)) {
1361 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
1362 }
1363 }
1364
1365 if ($this->_id) {
1366 $ids['membership'] = $params['id'] = $this->_id;
1367 }
1368
1369 $session = CRM_Core_Session::singleton();
1370 $ids['userId'] = $session->get('userID');
1371
1372 // membership type custom data
1373 foreach ($this->_memTypeSelected as $memType) {
1374 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
1375 $this->_id,
1376 'Membership'
1377 );
1378 }
1379
1380 foreach ($this->_memTypeSelected as $memType) {
1381 $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1382 $memType
1383 );
1384 }
1385
1386 $membershipType = implode(', ', $membershipTypes);
1387
1388 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1389 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
1390
1391 //CRM-13981, allow different person as a soft-contributor of chosen type
1392 if ($this->_contributorContactID != $this->_contactID) {
1393 $params['contribution_contact_id'] = $this->_contributorContactID;
1394 if (!empty($this->_params['soft_credit_type_id'])) {
1395 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
1396 $softParams['contact_id'] = $this->_contactID;
1397 }
1398 }
1399 if (!empty($formValues['record_contribution'])) {
1400 $recordContribution = array(
1401 'total_amount',
1402 'financial_type_id',
1403 'payment_instrument_id',
1404 'trxn_id',
1405 'contribution_status_id',
1406 'check_number',
1407 'campaign_id',
1408 'receive_date',
1409 );
1410
1411 foreach ($recordContribution as $f) {
1412 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1413 }
1414
1415 if (!$this->_onlinePendingContributionId) {
1416 if (empty($formValues['source'])) {
1417 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(
1418 1 => $membershipType,
1419 2 => $userName,
1420 ));
1421 }
1422 else {
1423 $params['contribution_source'] = $formValues['source'];
1424 }
1425 }
1426
1427 if (empty($params['is_override']) &&
1428 CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
1429 ) {
1430 $params['status_id'] = array_search('Pending', $allMemberStatus);
1431 $params['skipStatusCal'] = TRUE;
1432 $params['is_pay_later'] = 1;
1433 $this->assign('is_pay_later', 1);
1434 }
1435
1436 if (!empty($formValues['send_receipt'])) {
1437 $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
1438 }
1439
1440 //insert financial type name in receipt.
1441 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1442 $formValues['financial_type_id']
1443 );
1444 }
1445
1446 // process line items, until no previous line items.
1447 if (!empty($lineItem)) {
1448 $params['lineItems'] = $lineItem;
1449 $params['processPriceSet'] = TRUE;
1450 }
1451 $createdMemberships = array();
1452 if ($this->_mode) {
1453 if (empty($formValues['total_amount']) && !$priceSetID) {
1454 // if total amount not provided minimum for membership type is used
1455 $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1456 $formValues['membership_type_id'][1], 'minimum_fee'
1457 );
1458 }
1459 else {
1460 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
1461 }
1462
1463 if ($priceSetID && !$isQuickConfig) {
1464 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet',
1465 $priceSetID,
1466 'financial_type_id'
1467 );
1468 }
1469 else {
1470 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
1471 }
1472
1473 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'],
1474 $this->_mode
1475 );
1476
1477 //get the payment processor id as per mode.
1478 $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1479
1480 $now = date('YmdHis');
1481 $fields = array();
1482
1483 // set email for primary location.
1484 $fields['email-Primary'] = 1;
1485 $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
1486 $params['register_date'] = $now;
1487
1488 // now set the values for the billing location.
1489 foreach ($this->_fields as $name => $dontCare) {
1490 $fields[$name] = 1;
1491 }
1492
1493 // also add location name to the array
1494 $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);
1495
1496 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1497
1498 $fields["address_name-{$this->_bltID}"] = 1;
1499 //ensure we don't over-write the payer's email with the member's email
1500 if ($this->_contributorContactID == $this->_contactID) {
1501 $fields["email-{$this->_bltID}"] = 1;
1502 }
1503
1504 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
1505
1506 $nameFields = array('first_name', 'middle_name', 'last_name');
1507
1508 foreach ($nameFields as $name) {
1509 $fields[$name] = 1;
1510 if (array_key_exists("billing_$name", $formValues)) {
1511 $formValues[$name] = $formValues["billing_{$name}"];
1512 $formValues['preserveDBName'] = TRUE;
1513 }
1514 }
1515 if ($this->_contributorContactID == $this->_contactID) {
1516 //see CRM-12869 for discussion of why we don't do this for separate payee payments
1517 CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields,
1518 $this->_contributorContactID, NULL, NULL, $ctype
1519 );
1520 }
1521
1522 // add all the additional payment params we need
1523 $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}"]);
1524 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1525
1526 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1527 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1528 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1529 $this->_params['amount'] = $params['total_amount'];
1530 $this->_params['currencyID'] = $config->defaultCurrency;
1531 $this->_params['description'] = ts('Office Credit Card Membership Signup Contribution');
1532 $this->_params['payment_action'] = 'Sale';
1533 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1534 $this->_params['financial_type_id'] = $params['financial_type_id'];
1535
1536 // at this point we've created a contact and stored its address etc
1537 // all the payment processors expect the name and address to be in the
1538 // so we copy stuff over to first_name etc.
1539 $paymentParams = $this->_params;
1540 $paymentParams['contactID'] = $this->_contributorContactID;
1541 //CRM-10377 if payment is by an alternate contact then we need to set that person
1542 // as the contact in the payment params
1543 if ($this->_contributorContactID != $this->_contactID) {
1544 if (!empty($this->_params['soft_credit_type_id'])) {
1545 $softParams['contact_id'] = $params['contact_id'];
1546 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
1547 }
1548 }
1549 if (!empty($this->_params['send_receipt'])) {
1550 $paymentParams['email'] = $this->_contributorEmail;
1551 }
1552
1553 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1554
1555 // CRM-7137 -for recurring membership,
1556 // we do need contribution and recurring records.
1557 $result = NULL;
1558 if (!empty($paymentParams['is_recur'])) {
1559 $contributionType = new CRM_Financial_DAO_FinancialType();
1560 $contributionType->id = $params['financial_type_id'];
1561 if (!$contributionType->find(TRUE)) {
1562 CRM_Core_Error::fatal('Could not find a system table');
1563 }
1564
1565 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1566 $paymentParams,
1567 $result,
1568 $this->_contributorContactID,
1569 $contributionType,
1570 TRUE,
1571 FALSE,
1572 $isTest,
1573 $lineItems,
1574 $this->_bltID
1575 );
1576
1577 //create new soft-credit record, CRM-13981
1578 if ($softParams) {
1579 $softParams['contribution_id'] = $contribution->id;
1580 $softParams['currency'] = $contribution->currency;
1581 $softParams['amount'] = $contribution->total_amount;
1582 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1583 }
1584
1585 $paymentParams['contactID'] = $this->_contactID;
1586 $paymentParams['contributionID'] = $contribution->id;
1587 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1588 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1589 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1590 $ids['contribution'] = $contribution->id;
1591 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1592 }
1593
1594 if ($params['total_amount'] > 0.0) {
1595 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
1596 $result = $payment->doDirectPayment($paymentParams);
1597 }
1598
1599 if (is_a($result, 'CRM_Core_Error')) {
1600 //make sure to cleanup db for recurring case.
1601 if (!empty($paymentParams['contributionID'])) {
1602 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1603 }
1604 if (!empty($paymentParams['contributionRecurID'])) {
1605 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1606 }
1607
1608 CRM_Core_Error::displaySessionError($result);
1609 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
1610 "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
1611 ));
1612 }
1613
1614 if ($result) {
1615 $this->_params = array_merge($this->_params, $result);
1616 //assign amount to template if payment was successful
1617 $this->assign('amount', $params['total_amount']);
1618 }
1619
1620 // if the payment processor returns a contribution_status_id -> use it!
1621 if (isset($result['contribution_status_id'])) {
1622 $params['contribution_status_id'] = $result['contribution_status_id'];
1623 }
1624 // do what used to happen previously
1625 else {
1626 $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
1627 }
1628 if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
1629 $params['status_id'] = array_search('Pending', $allMemberStatus);
1630 $params['skipStatusCal'] = TRUE;
1631 // unset send-receipt option, since receipt will be sent when ipn is received.
1632 unset($this->_params['send_receipt'], $formValues['send_receipt']);
1633 //as membership is pending set dates to null.
1634 $memberDates = array(
1635 'join_date' => 'joinDate',
1636 'start_date' => 'startDate',
1637 'end_date' => 'endDate',
1638 );
1639 foreach ($memberDates as $dv) {
1640 $$dv = NULL;
1641 foreach ($this->_memTypeSelected as $memType) {
1642 $membershipTypeValues[$memType][$dv] = NULL;
1643 }
1644 }
1645 }
1646 $params['receive_date'] = $now;
1647 $params['invoice_id'] = $this->_params['invoiceID'];
1648 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1649 array(1 => $membershipType, 2 => $userName)
1650 );
1651 $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
1652 $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1653 $params['payment_instrument_id'] = 1;
1654 $params['is_test'] = ($this->_mode == 'live') ? 0 : 1;
1655 if (!empty($this->_params['send_receipt'])) {
1656 $params['receipt_date'] = $now;
1657 }
1658 else {
1659 $params['receipt_date'] = NULL;
1660 }
1661
1662 $this->set('params', $this->_params);
1663 $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
1664 $this->assign('receive_date',
1665 CRM_Utils_Date::mysqlToIso($params['receive_date'])
1666 );
1667
1668 // required for creating membership for related contacts
1669 $params['action'] = $this->_action;
1670
1671 //create membership record.
1672 $count = 0;
1673 foreach ($this->_memTypeSelected as $memType) {
1674 if ($count &&
1675 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1676 ) {
1677 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1678 }
1679
1680 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1681 //CRM-15366
1682 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1683 $membershipParams['soft_credit'] = $softParams;
1684 }
1685 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1686 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
1687 unset($params['lineItems']);
1688 $this->_membershipIDs[] = $membership->id;
1689 $createdMemberships[$memType] = $membership;
1690 $count++;
1691 }
1692
1693 }
1694 else {
1695 $params['action'] = $this->_action;
1696 if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
1697
1698 // update membership as well as contribution object, CRM-4395
1699 $params['contribution_id'] = $this->_onlinePendingContributionId;
1700 $params['componentId'] = $params['id'];
1701 $params['componentName'] = 'contribute';
1702 $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
1703 if (!empty($result) && !empty($params['contribution_id'])) {
1704 $lineItem = array();
1705 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
1706 $itemId = key($lineItems);
1707 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1708 $fieldType = NULL;
1709 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1710 $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1711 }
1712 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1713 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1714 $lineItems[$itemId]['id'] = $itemId;
1715 $lineItem[$priceSetId] = $lineItems;
1716 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1717 $contributionBAO->id = $params['contribution_id'];
1718 $contributionBAO->contact_id = $params['contact_id'];
1719 $contributionBAO->find();
1720 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1721
1722 //create new soft-credit record, CRM-13981
1723 if ($softParams) {
1724 $softParams['contribution_id'] = $params['contribution_id'];
1725 while ($contributionBAO->fetch()) {
1726 $softParams['currency'] = $contributionBAO->currency;
1727 $softParams['amount'] = $contributionBAO->total_amount;
1728 }
1729 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1730 }
1731 }
1732
1733 //carry updated membership object.
1734 $membership = new CRM_Member_DAO_Membership();
1735 $membership->id = $this->_id;
1736 $membership->find(TRUE);
1737
1738 $cancelled = TRUE;
1739 if ($membership->end_date) {
1740 //display end date w/ status message.
1741 $endDate = $membership->end_date;
1742
1743 if (!in_array($membership->status_id, array(
1744 // CRM-15475
1745 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1746 array_search('Expired', CRM_Member_PseudoConstant::membershipStatus()),
1747 ))
1748 ) {
1749 $cancelled = FALSE;
1750 }
1751 }
1752 // suppress form values in template.
1753 $this->assign('cancelled', $cancelled);
1754
1755 $createdMemberships[] = $membership;
1756 }
1757 else {
1758 $count = 0;
1759 foreach ($this->_memTypeSelected as $memType) {
1760 if ($count && !empty($formValues['record_contribution']) &&
1761 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1762 ) {
1763 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1764 }
1765
1766 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1767 if (!empty($formValues['int_amount'])) {
1768 $init_amount = array();
1769 foreach ($formValues as $key => $value) {
1770 if (strstr($key, 'txt-price')) {
1771 $init_amount[$key] = $value;
1772 }
1773 }
1774 $membershipParams['init_amount'] = $init_amount;
1775 }
1776
1777 if (!empty($softParams)) {
1778 $membershipParams['soft_credit'] = $softParams;
1779 }
1780
1781 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1782 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
1783 unset($params['lineItems']);
1784
1785 $this->_membershipIDs[] = $membership->id;
1786 $createdMemberships[$memType] = $membership;
1787 $count++;
1788 }
1789 }
1790 }
1791
1792 if (!empty($lineItem[$priceSetID])) {
1793 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1794 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1795 $taxAmount = FALSE;
1796 $totalTaxAmount = 0;
1797 foreach ($lineItem[$priceSetID] as & $priceFieldOp) {
1798 if (!empty($priceFieldOp['membership_type_id'])) {
1799 $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') : '-';
1800 $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') : '-';
1801 }
1802 else {
1803 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1804 }
1805 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1806 $taxAmount = TRUE;
1807 $totalTaxAmount += $priceFieldOp['tax_amount'];
1808 }
1809 }
1810 if ($invoicing) {
1811 $dataArray = array();
1812 foreach ($lineItem[$priceSetID] as $key => $value) {
1813 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1814 if (isset($dataArray[$value['tax_rate']])) {
1815 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1816 }
1817 else {
1818 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1819 }
1820 }
1821 }
1822 if ($taxAmount) {
1823 $this->assign('totalTaxAmount', $totalTaxAmount);
1824 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1825 }
1826 $this->assign('dataArray', $dataArray);
1827 }
1828 }
1829 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1830
1831 $receiptSend = FALSE;
1832 $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
1833 $membershipIds = $this->_membershipIDs;
1834 if ($contributionId && !empty($membershipIds)) {
1835 $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(
1836 CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
1837 if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
1838 $receiptSend = TRUE;
1839 }
1840 }
1841
1842 if (!empty($formValues['send_receipt']) && $receiptSend) {
1843 $formValues['contact_id'] = $this->_contactID;
1844 $formValues['contribution_id'] = $contributionId;
1845 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1846 // handled in the receipt. But by setting one we avoid breaking templates for now
1847 // although at some point we should switch in the templates.
1848 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1849 // send email receipt
1850 $mailSend = self::emailReceipt($this, $formValues, $membership);
1851 }
1852
1853 // finally set membership id if already not set
1854 if (!$this->_id) {
1855 $this->_id = $membership->id;
1856 }
1857
1858 $statusMsg = '';
1859 if (($this->_action & CRM_Core_Action::UPDATE)) {
1860 $statusMsg = $this->getStatusMessageForUpdate($membership, $endDate, $receiptSend);
1861
1862 }
1863 elseif (($this->_action & CRM_Core_Action::ADD)) {
1864 $statusMsg = $this->getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1865 $params, $calcDates, $mailSend);
1866 }
1867
1868 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1869
1870 return $createdMemberships;
1871 }
1872
1873 protected function setUserContext() {
1874 $buttonName = $this->controller->getButtonName();
1875 $session = CRM_Core_Session::singleton();
1876
1877 if ($this->_context == 'standalone') {
1878 if ($buttonName == $this->getButtonName('upload', 'new')) {
1879 $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add',
1880 'reset=1&action=add&context=standalone'
1881 ));
1882 }
1883 else {
1884 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1885 "reset=1&cid={$this->_contactID}&selectedChild=member"
1886 ));
1887 }
1888 }
1889 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1890 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership',
1891 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1892 ));
1893 }
1894 }
1895
1896 /**
1897 * @param $membership
1898 * @param $endDate
1899 * @param $receiptSend
1900 * @return string
1901 */
1902 protected function getStatusMessageForUpdate($membership, $endDate, $receiptSend) {
1903 //end date can be modified by hooks, so if end date is set then use it.
1904 $endDate = ($membership->end_date) ? $membership->end_date : $endDate;
1905
1906 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
1907 if ($endDate && $endDate !== 'null') {
1908 $endDate = CRM_Utils_Date::customFormat($endDate);
1909 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
1910 }
1911
1912 if ($receiptSend) {
1913 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
1914 }
1915 return $statusMsg;
1916 }
1917
1918 /**
1919 * @param $endDate
1920 * @param $receiptSend
1921 * @param $membershipTypes
1922 * @param $createdMemberships
1923 * @param $params
1924 * @param $calcDates
1925 * @param $mailSent
1926 * @internal param $membership
1927 * @return array|string
1928 */
1929 protected function getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1930 $params, $calcDates, $mailSent) {
1931 // FIX ME: fix status messages
1932
1933 $statusMsg = array();
1934 foreach ($membershipTypes as $memType => $membershipType) {
1935 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1936 1 => $membershipType,
1937 2 => $this->_memberDisplayName,
1938 ));
1939
1940 $membership = $createdMemberships[$memType];
1941 $memEndDate = ($membership->end_date) ? $membership->end_date : $endDate;
1942
1943 //get the end date from calculated dates.
1944 if (!$memEndDate && empty($params['is_recur'])) {
1945 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
1946 }
1947
1948 if ($memEndDate && $memEndDate !== 'null') {
1949 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
1950 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
1951 }
1952 }
1953 $statusMsg = implode('<br/>', $statusMsg);
1954 if ($receiptSend && $mailSent) {
1955 $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
1956 }
1957 return $statusMsg;
1958 }
1959
1960 }