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