0c5d0c0eda018cc2b0ce38cf781f7b757d44b1c8
[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 if ($this->_mode) {
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)) {
605 $sql = '
606 SELECT id,
607 auto_renew,
608 duration_unit,
609 duration_interval
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;
615 foreach (array(
616 'id',
617 'auto_renew',
618 'duration_unit',
619 'duration_interval',
620 ) as $fld) {
621 $this->_recurMembershipTypes[$recurMembershipTypes->id][$fld] = $recurMembershipTypes->$fld;
622 }
623 }
624 }
625 $memTypeJs = array(
626 'onChange' =>
627 "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );",
628 );
629 }
630 }
631 }
632 $allowAutoRenew = FALSE;
633 if ($this->_mode && !empty($recurProcessor)) {
634 $allowAutoRenew = TRUE;
635 }
636 $this->assign('allowAutoRenew', $allowAutoRenew);
637 $this->assign('autoRenewOptions', json_encode($autoRenew));
638 $this->assign('recurProcessor', json_encode($recurProcessor));
639
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')
644 );
645
646 $sel = &$this->addElement('hierselect',
647 'membership_type_id',
648 ts('Membership Organization and Type'),
649 $memTypeJs
650 );
651
652 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
653 $elements = array();
654 if ($sel) {
655 $elements[] = $sel;
656 }
657
658 $this->applyFilter('__ALL__', 'trim');
659
660 if ($this->_action & CRM_Core_Action::ADD) {
661 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
662 }
663
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'));
667 if ($endDate) {
668 $elements[] = $endDate;
669 }
670
671 $this->add('text', 'source', ts('Source'),
672 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source')
673 );
674
675 //CRM-7362 --add campaigns.
676 $campaignId = NULL;
677 if ($this->_id) {
678 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
679 }
680 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
681
682 if (!$this->_mode) {
683 $this->add('select', 'status_id', ts('Membership Status'),
684 array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
685 );
686 $statusOverride = $this->addElement('checkbox', 'is_override',
687 ts('Status Override?'), NULL,
688 array('onClick' => 'showHideMemberStatus()')
689 );
690 if ($statusOverride) {
691 $elements[] = $statusOverride;
692 }
693
694 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
695
696 $this->add('text', 'total_amount', ts('Amount'));
697 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
698
699 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
700
701 $this->add('select', 'payment_instrument_id',
702 ts('Paid By'),
703 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
704 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
705 );
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')
709 );
710
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(
717 'In Progress',
718 'Overdue',
719 ))
720 ) {
721 continue;
722 }
723 $allowStatuses[$val] = $statuses[$val];
724 }
725 }
726 else {
727 $allowStatuses = $statuses;
728 }
729 $this->add('select', 'contribution_status_id',
730 ts('Payment Status'), $allowStatuses
731 );
732 $this->add('text', 'check_number', ts('Check Number'),
733 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
734 );
735 }
736 else {
737 //add field for amount to allow an amount to be entered that differs from minimum
738 $this->add('text', 'total_amount', ts('Amount'));
739 }
740 $this->add('select', 'financial_type_id',
741 ts('Financial Type'),
742 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
743 );
744
745 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
746
747 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
748 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
749
750 $this->addElement('checkbox',
751 'send_receipt',
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);")
754 );
755
756 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
757
758 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
759
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,
763 $this->_memberEmail
764 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
765
766 $this->assign('emailExists', $this->_memberEmail);
767 $this->assign('displayName', $this->_memberDisplayName);
768 }
769
770 $isRecur = FALSE;
771 if ($this->_action & CRM_Core_Action::UPDATE) {
772 $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id,
773 'contribution_recur_id'
774 );
775 if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
776 $isRecur = TRUE;
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}")
780 );
781 }
782 foreach ($elements as $elem) {
783 $elem->freeze();
784 }
785 }
786 }
787 $this->assign('isRecur', $isRecur);
788
789 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
790
791 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
792 'mailing_backend'
793 );
794 $this->assign('outBound_option', $mailingInfo['outBound_option']);
795
796 parent::buildQuickForm();
797 }
798
799 /**
800 * Validation.
801 *
802 * @param array $params
803 * (ref.) an assoc array of name/value pairs.
804 *
805 * @param $files
806 * @param $self
807 *
808 * @throws CiviCRM_API3_Exception
809 * @return bool|array
810 * mixed true or array of errors
811 */
812 public static function formRule($params, $files, $self) {
813 $errors = array();
814
815 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
816
817 $selectedMemberships = self::getSelectedMemberships($priceSetId, $params);
818
819 if ($priceSetId) {
820 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
821
822 $priceFieldIDS = self::getPriceFieldIDs($params, $self);
823
824 if (!empty($priceFieldIDS)) {
825 $ids = implode(',', $priceFieldIDS);
826
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.');
831 }
832 }
833 }
834 }
835 elseif (empty($params['membership_type_id'][1])) {
836 $errors['membership_type_id'] = ts('Please select a membership type.');
837 }
838
839 if (!$priceSetId) {
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.');
843 }
844 }
845
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.');
849 }
850
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.');
857 }
858 }
859 }
860
861 if (!empty($errors)) {
862 return $errors;
863 }
864
865 if ($priceSetId && !$self->_mode && empty($params['record_contribution'])) {
866 $errors['record_contribution'] = ts('Record Membership Payment is required when you using price set.');
867 }
868
869 if (!$priceSetId && $self->_mode && empty($params['financial_type_id'])) {
870 $errors['financial_type_id'] = ts('Please enter the financial Type.');
871 }
872
873 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
874 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
875 }
876
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');
880 }
881 if (empty($params['soft_credit_contact_id'])) {
882 $errors['soft_credit_contact_id'] = ts('Please select a contact');
883 }
884 }
885
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);
889 }
890
891 $joinDate = NULL;
892 if (!empty($params['join_date'])) {
893
894 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
895
896 foreach ($selectedMemberships as $memType) {
897 $startDate = NULL;
898 if (!empty($params['start_date'])) {
899 $startDate = CRM_Utils_Date::processDate($params['start_date']);
900 }
901
902 // if end date is set, ensure that start date is also set
903 // and that end date is later than start date
904 $endDate = NULL;
905 if (!empty($params['end_date'])) {
906 $endDate = CRM_Utils_Date::processDate($params['end_date']);
907 }
908
909 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($memType);
910
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.');
914 }
915 }
916
917 if ($endDate) {
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(
922 'sequential' => 1,
923 'is_current_member' => 0,
924 ));
925 $tmp_statuses = $result['values'];
926 $status_ids = array();
927 foreach ($tmp_statuses as $cur_stat) {
928 $status_ids[] = $cur_stat['id'];
929 }
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');
933 }
934 }
935 else {
936 if (!$startDate) {
937 $errors['start_date'] = ts('Start date must be set if end date is set.');
938 }
939 if ($endDate < $startDate) {
940 $errors['end_date'] = ts('End date must be the same or later than start date.');
941 }
942 }
943 }
944
945 // Default values for start and end dates if not supplied
946 // on the form
947 $defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
948 $joinDate,
949 $startDate,
950 $endDate
951 );
952
953 if (!$startDate) {
954 $startDate = CRM_Utils_Array::value('start_date',
955 $defaultDates
956 );
957 }
958 if (!$endDate) {
959 $endDate = CRM_Utils_Array::value('end_date',
960 $defaultDates
961 );
962 }
963
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,
967 $endDate,
968 $joinDate,
969 'today',
970 TRUE,
971 $memType,
972 $params
973 );
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));
978 if (!$self->_mode) {
979 $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
980 }
981 CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
982 }
983 }
984 }
985 }
986 else {
987 $errors['join_date'] = ts('Please enter the Member Since.');
988 }
989
990 if (isset($params['is_override']) &&
991 $params['is_override'] && empty($params['status_id'])
992 ) {
993 $errors['status_id'] = ts('Please enter the status.');
994 }
995
996 //total amount condition arise when membership type having no
997 //minimum fee
998 if (isset($params['record_contribution'])) {
999 if (!$params['financial_type_id']) {
1000 $errors['financial_type_id'] = ts('Please enter the financial Type.');
1001 }
1002 if (CRM_Utils_System::isNull($params['total_amount'])) {
1003 $errors['total_amount'] = ts('Please enter the contribution.');
1004 }
1005 }
1006
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'))
1011 )
1012 ) {
1013 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
1014 }
1015
1016 return empty($errors) ? TRUE : $errors;
1017 }
1018
1019 /**
1020 * Process the form submission.
1021 */
1022 public function postProcess() {
1023 if ($this->_action & CRM_Core_Action::DELETE) {
1024 CRM_Member_BAO_Membership::del($this->_id);
1025 return;
1026 }
1027 // get the submitted form values.
1028 $this->_params = $this->controller->exportValues($this->_name);
1029
1030 $this->submit($this->_params);
1031
1032 $this->setUserContext();
1033 }
1034
1035 /**
1036 * Send email receipt.
1037 *
1038 * @param CRM_Core_Form $form
1039 * Form object.
1040 * @param array $formValues
1041 * @param object $membership
1042 * Object.
1043 *
1044 * @return bool
1045 * true if mail was sent successfully
1046 */
1047 public static function emailReceipt(&$form, &$formValues, &$membership) {
1048 // retrieve 'from email id' for acknowledgement
1049 $receiptFrom = $formValues['from_email_address'];
1050
1051 if (!empty($formValues['payment_instrument_id'])) {
1052 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1053 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
1054 }
1055
1056 // retrieve custom data
1057 $customFields = $customValues = array();
1058 if (property_exists($form, '_groupTree')
1059 && !empty($form->_groupTree)
1060 ) {
1061 foreach ($form->_groupTree as $groupID => $group) {
1062 if ($groupID == 'info') {
1063 continue;
1064 }
1065 foreach ($group['fields'] as $k => $field) {
1066 $field['title'] = $field['label'];
1067 $customFields["custom_{$k}"] = $field;
1068 }
1069 }
1070 }
1071
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);
1076 }
1077
1078 CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1079
1080 if ($form->_mode) {
1081 $name = '';
1082 if (!empty($form->_params['billing_first_name'])) {
1083 $name = $form->_params['billing_first_name'];
1084 }
1085
1086 if (!empty($form->_params['billing_middle_name'])) {
1087 $name .= " {$form->_params['billing_middle_name']}";
1088 }
1089
1090 if (!empty($form->_params['billing_last_name'])) {
1091 $name .= " {$form->_params['billing_last_name']}";
1092 }
1093
1094 $form->assign('billingName', $name);
1095
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}",
1103 );
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];
1109 }
1110 }
1111 $form->assign('address', CRM_Utils_Address::format($addressFields));
1112
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'])
1118 );
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);
1124 }
1125
1126 $form->assign('module', 'Membership');
1127 $form->assign('contactID', $formValues['contact_id']);
1128
1129 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
1130
1131 if (!empty($formValues['contribution_id'])) {
1132 $form->assign('contributionID', $formValues['contribution_id']);
1133 }
1134 elseif (isset($form->_onlinePendingContributionId)) {
1135 $form->assign('contributionID', $form->_onlinePendingContributionId);
1136 }
1137
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'));
1141 }
1142
1143 if (!empty($formValues['is_renew'])) {
1144 $form->assign('receiptType', 'membership renewal');
1145 }
1146 else {
1147 $form->assign('receiptType', 'membership signup');
1148 }
1149 $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues)));
1150 $form->assign('formValues', $formValues);
1151
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'));
1156 }
1157 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
1158 }
1159
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'];
1172 }
1173 }
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']))) {
1180 $isEmailPdf = TRUE;
1181 }
1182 else {
1183 $isEmailPdf = FALSE;
1184 }
1185
1186 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1187 array(
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),
1198 )
1199 );
1200
1201 return TRUE;
1202 }
1203
1204 /**
1205 * @param array $formValues
1206
1207 * @return array
1208 */
1209 public function submit($formValues) {
1210 $isTest = ($this->_mode == 'test') ? 1 : 0;
1211
1212 $joinDate = $startDate = $endDate = NULL;
1213 $membershipTypes = $membership = $calcDate = array();
1214 $membershipType = NULL;
1215
1216 $mailSend = FALSE;
1217 $priceSetID = CRM_Utils_Array::value('price_set_id', $formValues);
1218
1219 $params = $softParams = $ids = array();
1220
1221 $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
1222 $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
1223
1224 $lineItems = NULL;
1225 if (!empty($this->_lineItem)) {
1226 $lineItems = $this->_lineItem;
1227 }
1228
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);
1234
1235 $config = CRM_Core_Config::singleton();
1236
1237 $this->convertDateFieldsToMySQL($formValues);
1238
1239 $membershipTypeValues = array();
1240 foreach ($this->_memTypeSelected as $memType) {
1241 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1242 }
1243
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;
1247 $mapping = array(
1248 'frequency_interval' => 'duration_interval',
1249 'frequency_unit' => 'duration_unit',
1250 );
1251
1252 $count = 0;
1253 foreach ($this->_memTypeSelected as $memType) {
1254 $recurMembershipTypeValues = CRM_Utils_Array::value($memType,
1255 $this->_recurMembershipTypes, array()
1256 );
1257 foreach ($mapping as $mapVal => $mapParam) {
1258 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam,
1259 $recurMembershipTypeValues
1260 );
1261 if (!$count) {
1262 $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam,
1263 $recurMembershipTypeValues
1264 );
1265 }
1266 }
1267 $count++;
1268 }
1269 }
1270
1271 // process price set and get total amount and line items.
1272 $lineItem = array();
1273 if ($priceSetID) {
1274 CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetID);
1275 }
1276 $isQuickConfig = 0;
1277 if ($priceSetID && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetID, 'is_quick_config')) {
1278 $isQuickConfig = 1;
1279 }
1280
1281 $termsByType = array();
1282 if ($priceSetID) {
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'];
1287 }
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'];
1295 }
1296 }
1297
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;
1303 }
1304 }
1305 }
1306 }
1307
1308 $this->storeContactFields($formValues);
1309
1310 $params['contact_id'] = $this->_contactID;
1311
1312 $fields = array(
1313 'status_id',
1314 'source',
1315 'is_override',
1316 'campaign_id',
1317 );
1318
1319 foreach ($fields as $f) {
1320 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1321 }
1322
1323 // fix for CRM-3724
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;
1328 }
1329
1330 // process date params to mysql date format.
1331 $dateTypes = array(
1332 'join_date' => 'joinDate',
1333 'start_date' => 'startDate',
1334 'end_date' => 'endDate',
1335 );
1336 foreach ($dateTypes as $dateField => $dateVariable) {
1337 $$dateVariable = CRM_Utils_Date::processDate($formValues[$dateField]);
1338 }
1339
1340 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
1341
1342 $calcDates = array();
1343 foreach ($this->_memTypeSelected as $memType) {
1344 if (empty($memTypeNumTerms)) {
1345 $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
1346 }
1347 $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
1348 $joinDate, $startDate, $endDate, $memTypeNumTerms
1349 );
1350 }
1351
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);
1356 if (!$date) {
1357 $date = CRM_Utils_Array::value($d, $calcDate);
1358 }
1359
1360 $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
1361 //$params[$d] = CRM_Utils_Date::processDate( $date );
1362 }
1363 }
1364
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);
1369 }
1370 }
1371
1372 if ($this->_id) {
1373 $ids['membership'] = $params['id'] = $this->_id;
1374 }
1375
1376 $session = CRM_Core_Session::singleton();
1377 $ids['userId'] = $session->get('userID');
1378
1379 // membership type custom data
1380 foreach ($this->_memTypeSelected as $memType) {
1381 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
1382 $this->_id,
1383 'Membership'
1384 );
1385 }
1386
1387 foreach ($this->_memTypeSelected as $memType) {
1388 $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1389 $memType
1390 );
1391 }
1392
1393 $membershipType = implode(', ', $membershipTypes);
1394
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']);
1397
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;
1404 }
1405 }
1406 if (!empty($formValues['record_contribution'])) {
1407 $recordContribution = array(
1408 'total_amount',
1409 'financial_type_id',
1410 'payment_instrument_id',
1411 'trxn_id',
1412 'contribution_status_id',
1413 'check_number',
1414 'campaign_id',
1415 'receive_date',
1416 );
1417
1418 foreach ($recordContribution as $f) {
1419 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1420 }
1421
1422 if (!$this->_onlinePendingContributionId) {
1423 if (empty($formValues['source'])) {
1424 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(
1425 1 => $membershipType,
1426 2 => $userName,
1427 ));
1428 }
1429 else {
1430 $params['contribution_source'] = $formValues['source'];
1431 }
1432 }
1433
1434 if (empty($params['is_override']) &&
1435 CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
1436 ) {
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);
1441 }
1442
1443 if (!empty($formValues['send_receipt'])) {
1444 $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
1445 }
1446
1447 //insert financial type name in receipt.
1448 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1449 $formValues['financial_type_id']
1450 );
1451 }
1452
1453 // process line items, until no previous line items.
1454 if (!empty($lineItem)) {
1455 $params['lineItems'] = $lineItem;
1456 $params['processPriceSet'] = TRUE;
1457 }
1458 $createdMemberships = array();
1459 if ($this->_mode) {
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'
1464 );
1465 }
1466 else {
1467 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
1468 }
1469
1470 if ($priceSetID && !$isQuickConfig) {
1471 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet',
1472 $priceSetID,
1473 'financial_type_id'
1474 );
1475 }
1476 else {
1477 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
1478 }
1479
1480 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'],
1481 $this->_mode
1482 );
1483
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'];
1486
1487 $now = date('YmdHis');
1488 $fields = array();
1489
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;
1494
1495 // now set the values for the billing location.
1496 foreach ($this->_fields as $name => $dontCare) {
1497 $fields[$name] = 1;
1498 }
1499
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);
1502
1503 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
1504
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;
1509 }
1510
1511 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
1512
1513 $nameFields = array('first_name', 'middle_name', 'last_name');
1514
1515 foreach ($nameFields as $name) {
1516 $fields[$name] = 1;
1517 if (array_key_exists("billing_$name", $formValues)) {
1518 $formValues[$name] = $formValues["billing_{$name}"];
1519 $formValues['preserveDBName'] = TRUE;
1520 }
1521 }
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
1526 );
1527 }
1528
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}"]);
1532
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'];
1542
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'];
1554 }
1555 }
1556 if (!empty($this->_params['send_receipt'])) {
1557 $paymentParams['email'] = $this->_contributorEmail;
1558 }
1559
1560 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1561
1562 // CRM-7137 -for recurring membership,
1563 // we do need contribution and recurring records.
1564 $result = NULL;
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');
1570 }
1571
1572 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1573 $paymentParams,
1574 $result,
1575 $this->_contributorContactID,
1576 $contributionType,
1577 TRUE,
1578 FALSE,
1579 $isTest,
1580 $lineItems,
1581 $this->_bltID
1582 );
1583
1584 //create new soft-credit record, CRM-13981
1585 if ($softParams) {
1586 $softParams['contribution_id'] = $contribution->id;
1587 $softParams['currency'] = $contribution->currency;
1588 $softParams['amount'] = $contribution->total_amount;
1589 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1590 }
1591
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'];
1599 }
1600
1601 if ($params['total_amount'] > 0.0) {
1602 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
1603 $result = $payment->doDirectPayment($paymentParams);
1604 }
1605
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']);
1610 }
1611 if (!empty($paymentParams['contributionRecurID'])) {
1612 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1613 }
1614
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}"
1618 ));
1619 }
1620
1621 if ($result) {
1622 $this->_params = array_merge($this->_params, $result);
1623 //assign amount to template if payment was successful
1624 $this->assign('amount', $params['total_amount']);
1625 }
1626
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'];
1630 }
1631 // do what used to happen previously
1632 else {
1633 $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
1634 }
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',
1645 );
1646 foreach ($memberDates as $dv) {
1647 $$dv = NULL;
1648 foreach ($this->_memTypeSelected as $memType) {
1649 $membershipTypeValues[$memType][$dv] = NULL;
1650 }
1651 }
1652 }
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)
1657 );
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;
1664 }
1665 else {
1666 $params['receipt_date'] = NULL;
1667 }
1668
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'])
1673 );
1674
1675 // required for creating membership for related contacts
1676 $params['action'] = $this->_action;
1677
1678 //create membership record.
1679 $count = 0;
1680 foreach ($this->_memTypeSelected as $memType) {
1681 if ($count &&
1682 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1683 ) {
1684 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1685 }
1686
1687 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1688 //CRM-15366
1689 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1690 $membershipParams['soft_credit'] = $softParams;
1691 }
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;
1697 $count++;
1698 }
1699
1700 }
1701 else {
1702 $params['action'] = $this->_action;
1703 if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
1704
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');
1715 $fieldType = NULL;
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');
1718 }
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');
1728
1729 //create new soft-credit record, CRM-13981
1730 if ($softParams) {
1731 $softParams['contribution_id'] = $params['contribution_id'];
1732 while ($contributionBAO->fetch()) {
1733 $softParams['currency'] = $contributionBAO->currency;
1734 $softParams['amount'] = $contributionBAO->total_amount;
1735 }
1736 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1737 }
1738 }
1739
1740 //carry updated membership object.
1741 $membership = new CRM_Member_DAO_Membership();
1742 $membership->id = $this->_id;
1743 $membership->find(TRUE);
1744
1745 $cancelled = TRUE;
1746 if ($membership->end_date) {
1747 //display end date w/ status message.
1748 $endDate = $membership->end_date;
1749
1750 if (!in_array($membership->status_id, array(
1751 // CRM-15475
1752 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1753 array_search('Expired', CRM_Member_PseudoConstant::membershipStatus()),
1754 ))
1755 ) {
1756 $cancelled = FALSE;
1757 }
1758 }
1759 // suppress form values in template.
1760 $this->assign('cancelled', $cancelled);
1761
1762 $createdMemberships[] = $membership;
1763 }
1764 else {
1765 $count = 0;
1766 foreach ($this->_memTypeSelected as $memType) {
1767 if ($count && !empty($formValues['record_contribution']) &&
1768 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1769 ) {
1770 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1771 }
1772
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;
1779 }
1780 }
1781 $membershipParams['init_amount'] = $init_amount;
1782 }
1783
1784 if (!empty($softParams)) {
1785 $membershipParams['soft_credit'] = $softParams;
1786 }
1787
1788 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
1789 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
1790 unset($params['lineItems']);
1791
1792 $this->_membershipIDs[] = $membership->id;
1793 $createdMemberships[$memType] = $membership;
1794 $count++;
1795 }
1796 }
1797 }
1798
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);
1802 $taxAmount = FALSE;
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') : '-';
1808 }
1809 else {
1810 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1811 }
1812 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1813 $taxAmount = TRUE;
1814 $totalTaxAmount += $priceFieldOp['tax_amount'];
1815 }
1816 }
1817 if ($invoicing) {
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);
1823 }
1824 else {
1825 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1826 }
1827 }
1828 }
1829 if ($taxAmount) {
1830 $this->assign('totalTaxAmount', $totalTaxAmount);
1831 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1832 }
1833 $this->assign('dataArray', $dataArray);
1834 }
1835 }
1836 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1837
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;
1846 }
1847 }
1848
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);
1858 }
1859
1860 // finally set membership id if already not set
1861 if (!$this->_id) {
1862 $this->_id = $membership->id;
1863 }
1864
1865 $statusMsg = '';
1866 if (($this->_action & CRM_Core_Action::UPDATE)) {
1867 $statusMsg = $this->getStatusMessageForUpdate($membership, $endDate, $receiptSend);
1868
1869 }
1870 elseif (($this->_action & CRM_Core_Action::ADD)) {
1871 $statusMsg = $this->getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1872 $params, $calcDates, $mailSend);
1873 }
1874
1875 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1876
1877 return $createdMemberships;
1878 }
1879
1880 protected function setUserContext() {
1881 $buttonName = $this->controller->getButtonName();
1882 $session = CRM_Core_Session::singleton();
1883
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'
1888 ));
1889 }
1890 else {
1891 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1892 "reset=1&cid={$this->_contactID}&selectedChild=member"
1893 ));
1894 }
1895 }
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}"
1899 ));
1900 }
1901 }
1902
1903 /**
1904 * @param $membership
1905 * @param $endDate
1906 * @param $receiptSend
1907 * @return string
1908 */
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;
1912
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));
1917 }
1918
1919 if ($receiptSend) {
1920 $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
1921 }
1922 return $statusMsg;
1923 }
1924
1925 /**
1926 * @param $endDate
1927 * @param $receiptSend
1928 * @param $membershipTypes
1929 * @param $createdMemberships
1930 * @param $params
1931 * @param $calcDates
1932 * @param $mailSent
1933 * @internal param $membership
1934 * @return array|string
1935 */
1936 protected function getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
1937 $params, $calcDates, $mailSent) {
1938 // FIX ME: fix status messages
1939
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,
1945 ));
1946
1947 $membership = $createdMemberships[$memType];
1948 $memEndDate = ($membership->end_date) ? $membership->end_date : $endDate;
1949
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]);
1953 }
1954
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));
1958 }
1959 }
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));
1963 }
1964 return $statusMsg;
1965 }
1966
1967 }