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