Merge pull request #10350 from seanmadsen/CRM-20570
[civicrm-core.git] / CRM / Contribute / Form / ContributionBase.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33
34/**
f92d1e2a 35 * This class generates form components for processing a contribution.
6a488035
TO
36 */
37class CRM_Contribute_Form_ContributionBase extends CRM_Core_Form {
38
39 /**
f92d1e2a 40 * The id of the contribution page that we are processing.
6a488035
TO
41 *
42 * @var int
6a488035
TO
43 */
44 public $_id;
45
46 /**
100fef9d 47 * The mode that we are in
6a488035
TO
48 *
49 * @var string
50 * @protect
51 */
52 public $_mode;
53
54 /**
100fef9d 55 * The contact id related to a membership
6a488035
TO
56 *
57 * @var int
6a488035
TO
58 */
59 public $_membershipContactID;
60
61 /**
100fef9d 62 * The values for the contribution db object
6a488035
TO
63 *
64 * @var array
6a488035
TO
65 */
66 public $_values;
67
68 /**
100fef9d 69 * The paymentProcessor attributes for this page
6a488035
TO
70 *
71 * @var array
6a488035
TO
72 */
73 public $_paymentProcessor;
1b9f9ca3 74
6a488035
TO
75 public $_paymentObject = NULL;
76
77 /**
78 * The membership block for this page
79 *
80 * @var array
6a488035
TO
81 */
82 public $_membershipBlock = NULL;
83
f64a217a
EM
84 /**
85 * Does this form support a separate membership payment
86 * @var bool
87 */
88 protected $_separateMembershipPayment;
6a488035
TO
89
90 /**
91 * The params submitted by the form and computed by the app
92 *
93 * @var array
6a488035 94 */
90102a32 95 public $_params = array();
6a488035
TO
96
97 /**
98 * The fields involved in this contribution page
99 *
100 * @var array
6a488035 101 */
532ee86f 102 public $_fields = array();
6a488035
TO
103
104 /**
f92d1e2a 105 * The billing location id for this contribution page.
6a488035
TO
106 *
107 * @var int
6a488035
TO
108 */
109 public $_bltID;
110
111 /**
112 * Cache the amount to make things easier
113 *
114 * @var float
6a488035
TO
115 */
116 public $_amount;
117
118 /**
100fef9d 119 * Pcp id
6a488035
TO
120 *
121 * @var integer
6a488035
TO
122 */
123 public $_pcpId;
124
125 /**
100fef9d 126 * Pcp block
6a488035
TO
127 *
128 * @var array
6a488035
TO
129 */
130 public $_pcpBlock;
131
132 /**
100fef9d 133 * Pcp info
6a488035
TO
134 *
135 * @var array
6a488035
TO
136 */
137 public $_pcpInfo;
138
5b757295 139 /**
140 * The contact id of the person for whom membership is being added or renewed based on the cid in the url,
141 * checksum, or session
0e5e0c2e 142 * @var int
5b757295 143 */
0e5e0c2e 144 public $_contactID;
5b757295 145
6a488035
TO
146 protected $_userID;
147
148 /**
100fef9d 149 * The Membership ID for membership renewal
6a488035
TO
150 *
151 * @var int
6a488035
TO
152 */
153 public $_membershipId;
154
155 /**
156 * Price Set ID, if the new price set method is used
157 *
158 * @var int
6a488035
TO
159 */
160 public $_priceSetId;
161
162 /**
163 * Array of fields for the price set
164 *
165 * @var array
6a488035
TO
166 */
167 public $_priceSet;
168
169 public $_action;
170
dbddfb08
EM
171 /**
172 * Contribution mode e.g express for payment express, notify for off-site + notification back to CiviCRM
173 * @var string
174 */
175 public $_contributeMode;
176
177 /**
100fef9d 178 * Contribution page supports memberships
dbddfb08
EM
179 * @var boolean
180 */
181 public $_useForMember;
8ae4d0d3 182
0f2b049e 183 /**
184 * @deprecated
185 *
186 * @var
187 */
8ae4d0d3 188 public $_isBillingAddressRequiredForPayLater;
353ffa53 189
0c7c9ff7
KC
190 /**
191 * Flag if email field exists in embedded profile
192 *
193 * @var bool
194 */
195 public $_emailExists = FALSE;
196
18135422 197 /**
198 * Is this a backoffice form
199 * (this will affect whether paypal express code is displayed)
200 * @var bool
201 */
202 public $isBackOffice = FALSE;
203
204 /**
205 * Payment instrument if for the transaction.
206 *
207 * This will generally be drawn from the payment processor and is ignored for
208 * front end forms.
209 *
210 * @var int
211 */
212 public $paymentInstrumentID;
213
6a488035 214 /**
fe482240 215 * Set variables up before form is built.
6a488035 216 *
7fe37828
EM
217 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
218 * @throws \Exception
6a488035
TO
219 */
220 public function preProcess() {
6a488035
TO
221
222 // current contribution page id
223 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
37e877b2 224 $this->_ccid = CRM_Utils_Request::retrieve('ccid', 'Positive', $this);
6a488035 225 if (!$this->_id) {
d420cf02
DL
226 // seems like the session is corrupted and/or we lost the id trail
227 // lets just bump this to a regular session error and redirect user to main page
228 $this->controller->invalidKeyRedirect();
6a488035 229 }
d420cf02 230
5b757295 231 // this was used prior to the cleverer this_>getContactID - unsure now
a6c15c46 232 $this->_userID = CRM_Core_Session::singleton()->get('userID');
5b757295 233
234 $this->_contactID = $this->_membershipContactID = $this->getContactID();
6a488035 235 $this->_mid = NULL;
5b757295 236 if ($this->_contactID) {
6a488035
TO
237 $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
238 if ($this->_mid) {
239 $membership = new CRM_Member_DAO_Membership();
240 $membership->id = $this->_mid;
241
242 if ($membership->find(TRUE)) {
243 $this->_defaultMemTypeId = $membership->membership_type_id;
5b757295 244 if ($membership->contact_id != $this->_contactID) {
6fe8deba 245 $validMembership = FALSE;
33260076 246 $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, NULL, NULL, 'Organization');
247 if (!empty($organizations) && array_key_exists($membership->contact_id, $organizations)) {
6fe8deba
DS
248 $this->_membershipContactID = $membership->contact_id;
249 $this->assign('membershipContactID', $this->_membershipContactID);
33260076 250 $this->assign('membershipContactName', $organizations[$this->_membershipContactID]['name']);
6fe8deba 251 $validMembership = TRUE;
0db6c3e1
TO
252 }
253 else {
51e89def
DS
254 $membershipType = new CRM_Member_BAO_MembershipType();
255 $membershipType->id = $membership->membership_type_id;
256 if ($membershipType->find(TRUE)) {
f9f0eff9 257 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
f92d1e2a 258 // Convert to comma separated list.
f9f0eff9 259 $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
51e89def
DS
260 $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
261 if (array_key_exists($membership->contact_id, $permContacts)) {
262 $this->_membershipContactID = $membership->contact_id;
6fe8deba 263 $validMembership = TRUE;
51e89def
DS
264 }
265 }
6a488035 266 }
6fe8deba
DS
267 if (!$validMembership) {
268 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
269 }
6a488035
TO
270 }
271 }
272 else {
273 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
274 }
275 unset($membership);
276 }
277 }
278
279 // we do not want to display recently viewed items, so turn off
280 $this->assign('displayRecent', FALSE);
281 // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
282 // Use Browser Print instead.
283 $this->assign('browserPrint', TRUE);
284
285 // action
286 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
287 $this->assign('action', $this->_action);
288
289 // current mode
290 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
291
292 $this->_values = $this->get('values');
293 $this->_fields = $this->get('fields');
294 $this->_bltID = $this->get('bltID');
295 $this->_paymentProcessor = $this->get('paymentProcessor');
296 $this->_priceSetId = $this->get('priceSetId');
297 $this->_priceSet = $this->get('priceSet');
298
299 if (!$this->_values) {
300 // get all the values from the dao object
301 $this->_values = array();
302 $this->_fields = array();
303
304 CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
40c655aa 305 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
66af7c48
PN
306 && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']))
307 ) {
0799e1c4
E
308 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
309 }
a7488080 310 if (empty($this->_values['is_active'])) {
4b57bc9f 311 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id);
6a488035
TO
312 }
313
8345c9d3 314 $this->assignBillingType();
6a488035
TO
315
316 // check for is_monetary status
317 $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values);
318 $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values);
24cf7458 319 if (!empty($this->_ccid)) {
320 $this->_values['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
321 $this->_ccid,
322 'financial_type_id'
323 );
324 if ($isPayLater) {
325 $isPayLater = FALSE;
326 $this->_values['is_pay_later'] = FALSE;
327 }
37e877b2 328 }
6a488035 329
6a488035 330 if ($isMonetary &&
8cc574cf 331 (!$isPayLater || !empty($this->_values['payment_processor']))
6a488035 332 ) {
a6c15c46
EM
333 $this->_paymentProcessorIDs = explode(
334 CRM_Core_DAO::VALUE_SEPARATOR,
335 CRM_Utils_Array::value('payment_processor', $this->_values)
1b9f9ca3 336 );
f92d1e2a 337
cbcb5b49 338 $this->assignPaymentProcessor($isPayLater);
6a488035
TO
339 }
340
341 // get price info
342 // CRM-5095
9da8dc8c 343 CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page');
6a488035
TO
344
345 // this avoids getting E_NOTICE errors in php
346 $setNullFields = array(
347 'amount_block_is_active',
6a488035
TO
348 'is_allow_other_amount',
349 'footer_text',
350 );
351 foreach ($setNullFields as $f) {
352 if (!isset($this->_values[$f])) {
353 $this->_values[$f] = NULL;
354 }
355 }
356
357 //check if Membership Block is enabled, if Membership Fields are included in profile
358 //get membership section for this contribution page
359 $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
360 $this->set('membershipBlock', $this->_membershipBlock);
361
4779abb3 362 if (!empty($this->_values['custom_pre_id'])) {
6a488035
TO
363 $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
364 }
365
4779abb3 366 if (!empty($this->_values['custom_post_id'])) {
6a488035
TO
367 $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
368 }
369
370 if (((isset($postProfileType) && $postProfileType == 'Membership') ||
371 (isset($preProfileType) && $preProfileType == 'Membership')
372 ) &&
373 !$this->_membershipBlock['is_active']
374 ) {
375 CRM_Core_Error::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
376 }
377
378 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
379
380 if ($pledgeBlock) {
381 $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock);
382 $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock);
383 $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock);
384 $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock);
385
386 //set pledge id in values
387 $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
388
389 //authenticate pledge user for pledge payment.
390 if ($pledgeId) {
391 $this->_values['pledge_id'] = $pledgeId;
392
393 //lets override w/ pledge campaign.
394 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
395 $pledgeId,
396 'campaign_id'
397 );
398 self::authenticatePledgeUser();
399 }
400 }
401 $this->set('values', $this->_values);
402 $this->set('fields', $this->_fields);
403 }
404
405 // Handle PCP
406 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
407 if ($pcpId) {
353ffa53
TO
408 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
409 $this->_pcpId = $pcp['pcpId'];
6a488035 410 $this->_pcpBlock = $pcp['pcpBlock'];
353ffa53 411 $this->_pcpInfo = $pcp['pcpInfo'];
6a488035
TO
412 }
413
414 // Link (button) for users to create their own Personal Campaign page
415 if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
416 $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign',
417 "action=add&reset=1&pageId={$this->_id}&component=contribute",
418 FALSE, NULL, TRUE
419 );
420 $this->assign('linkTextUrl', $linkTextUrl);
421 $this->assign('linkText', $linkText);
422 }
423
424 //set pledge block if block id is set
a7488080 425 if (!empty($this->_values['pledge_block_id'])) {
6a488035
TO
426 $this->assign('pledgeBlock', TRUE);
427 }
428
f92d1e2a 429 // check if one of the (amount , membership) blocks is active or not.
6a488035
TO
430 $this->_membershipBlock = $this->get('membershipBlock');
431
432 if (!$this->_values['amount_block_is_active'] &&
433 !$this->_membershipBlock['is_active'] &&
434 !$this->_priceSetId
435 ) {
436 CRM_Core_Error::fatal(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.'));
437 }
438
439 if ($this->_values['amount_block_is_active']) {
440 $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
441 }
442
443 $this->_contributeMode = $this->get('contributeMode');
444 $this->assign('contributeMode', $this->_contributeMode);
445
446 //assigning is_monetary and is_email_receipt to template
447 $this->assign('is_monetary', $this->_values['is_monetary']);
448 $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
449 $this->assign('bltID', $this->_bltID);
450
451 //assign cancelSubscription URL to templates
452 $this->assign('cancelSubscriptionUrl',
453 CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)
454 );
455
456 // assigning title to template in case someone wants to use it, also setting CMS page title
457 if ($this->_pcpId) {
458 $this->assign('title', $this->_pcpInfo['title']);
459 CRM_Utils_System::setTitle($this->_pcpInfo['title']);
460 }
461 else {
462 $this->assign('title', $this->_values['title']);
463 CRM_Utils_System::setTitle($this->_values['title']);
464 }
465 $this->_defaults = array();
466
467 $this->_amount = $this->get('amount');
468
469 //CRM-6907
470 $config = CRM_Core_Config::singleton();
471 $config->defaultCurrency = CRM_Utils_Array::value('currency',
472 $this->_values,
473 $config->defaultCurrency
474 );
475
476 //lets allow user to override campaign.
477 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
478 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
479 $this->_values['campaign_id'] = $campID;
480 }
481
482 //do check for cancel recurring and clean db, CRM-7696
a3d827a7 483 if (CRM_Utils_Request::retrieve('cancel', 'Boolean')) {
6a488035
TO
484 self::cancelRecurring();
485 }
8ae4d0d3 486
487 // check if billing block is required for pay later
488 if (CRM_Utils_Array::value('is_pay_later', $this->_values)) {
489 $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values);
490 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
491 }
6a488035
TO
492 }
493
494 /**
fe482240 495 * Set the default values.
6a488035 496 */
00be9182 497 public function setDefaultValues() {
6a488035
TO
498 return $this->_defaults;
499 }
500
501 /**
fe482240 502 * Assign the minimal set of variables to the template.
6a488035 503 */
00be9182 504 public function assignToTemplate() {
0b50eca0 505 $this->set('name', $this->assignBillingName($this->_params));
6a488035
TO
506
507 $this->assign('paymentProcessor', $this->_paymentProcessor);
508 $vars = array(
353ffa53
TO
509 'amount',
510 'currencyID',
511 'credit_card_type',
512 'trxn_id',
513 'amount_level',
6a488035
TO
514 );
515
516 $config = CRM_Core_Config::singleton();
8cc574cf 517 if (isset($this->_values['is_recur']) && !empty($this->_paymentProcessor['is_recur'])) {
6a488035
TO
518 $this->assign('is_recur_enabled', 1);
519 $vars = array_merge($vars, array(
353ffa53
TO
520 'is_recur',
521 'frequency_interval',
522 'frequency_unit',
523 'installments',
524 ));
6a488035
TO
525 }
526
527 if (in_array('CiviPledge', $config->enableComponents) &&
528 CRM_Utils_Array::value('is_pledge', $this->_params) == 1
529 ) {
530 $this->assign('pledge_enabled', 1);
531
532 $vars = array_merge($vars, array(
533 'is_pledge',
353ffa53
TO
534 'pledge_frequency_interval',
535 'pledge_frequency_unit',
536 'pledge_installments',
537 ));
6a488035
TO
538 }
539
c039f658 540 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
541 // function to get correct amount level consistently. Remove setting of the amount level in
542 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
543 // to cover all variants.
6a488035
TO
544 if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
545 $this->_params['amount_level'] = '';
546 }
547
548 foreach ($vars as $v) {
3fb990f4 549 if (isset($this->_params[$v])) {
735fe42d
PJ
550 if ($v == "amount" && $this->_params[$v] === 0) {
551 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
3fb990f4 552 }
6a488035
TO
553 $this->assign($v, $this->_params[$v]);
554 }
555 }
556
0b50eca0 557 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
558 $this->_params,
559 $this->_bltID
560 ));
6a488035 561
cb804cd9 562 if (!empty($this->_params['onbehalf_profile_id']) && !empty($this->_params['onbehalf'])) {
6a488035
TO
563 $this->assign('onBehalfName', $this->_params['organization_name']);
564 $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
565 $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
566 }
567
568 //fix for CRM-3767
569 $assignCCInfo = FALSE;
570 if ($this->_amount > 0.0) {
571 $assignCCInfo = TRUE;
572 }
a7488080 573 elseif (!empty($this->_params['selectMembership'])) {
6a488035
TO
574 $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
575 if ($memFee > 0.0) {
576 $assignCCInfo = TRUE;
577 }
578 }
579
0f2b049e 580 // The concept of contributeMode is deprecated.
581 // The payment processor object can provide info about the fields it shows.
6a488035 582 if ($this->_contributeMode == 'direct' && $assignCCInfo) {
f92fc7eb
CW
583 if ($this->_paymentProcessor &&
584 $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
585 ) {
6a488035
TO
586 $this->assign('account_holder', $this->_params['account_holder']);
587 $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
588 $this->assign('bank_name', $this->_params['bank_name']);
589 $this->assign('bank_account_number', $this->_params['bank_account_number']);
590 }
591 else {
35522279 592 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $this->_params));
6a488035
TO
593 $date = CRM_Utils_Date::mysqlToIso($date);
594 $this->assign('credit_card_exp_date', $date);
595 $this->assign('credit_card_number',
35522279 596 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $this->_params))
6a488035
TO
597 );
598 }
599 }
600
601 $this->assign('email',
602 $this->controller->exportValue('Main', "email-{$this->_bltID}")
603 );
604
605 // also assign the receipt_text
606 if (isset($this->_values['receipt_text'])) {
607 $this->assign('receipt_text', $this->_values['receipt_text']);
608 }
609 }
610
611 /**
fe482240 612 * Add the custom fields.
6a488035 613 *
100fef9d
CW
614 * @param int $id
615 * @param string $name
f4aaa82a
EM
616 * @param bool $viewOnly
617 * @param null $profileContactType
f92d1e2a 618 * @param array $fieldTypes
6a488035 619 */
00be9182 620 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
6a488035 621 if ($id) {
da8d9879 622 $contactID = $this->getContactID();
6a488035
TO
623
624 // we don't allow conflicting fields to be
625 // configured via profile - CRM 2100
626 $fieldsToIgnore = array(
627 'receive_date' => 1,
628 'trxn_id' => 1,
629 'invoice_id' => 1,
630 'net_amount' => 1,
631 'fee_amount' => 1,
632 'non_deductible_amount' => 1,
633 'total_amount' => 1,
634 'amount_level' => 1,
635 'contribution_status_id' => 1,
7bc1d4da 636 // @todo replace payment_instrument with payment instrument id.
637 // both are available now but the id field is the most consistent.
6a488035 638 'payment_instrument' => 1,
7bc1d4da 639 'payment_instrument_id' => 1,
640 'contribution_check_number' => 1,
6a488035
TO
641 'financial_type' => 1,
642 );
643
423b9af4 644 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
645 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
646 );
6a488035
TO
647
648 if ($fields) {
0c7c9ff7
KC
649 // determine if email exists in profile so we know if we need to manually insert CRM-2888, CRM-15067
650 foreach ($fields as $key => $field) {
651 if (substr($key, 0, 6) == 'email-' &&
652 !in_array($profileContactType, array('honor', 'onbehalf'))
653 ) {
654 $this->_emailExists = TRUE;
6a488035
TO
655 }
656 }
657
658 if (array_intersect_key($fields, $fieldsToIgnore)) {
659 $fields = array_diff_key($fields, $fieldsToIgnore);
660 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
661 }
662
d7d630be 663 //remove common fields only if profile is not configured for onbehalf/honor
664 if (!in_array($profileContactType, array('honor', 'onbehalf'))) {
94e01524 665 $fields = array_diff_key($fields, $this->_fields);
d7d630be 666 }
6a488035
TO
667
668 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
669 $addCaptcha = FALSE;
f3726153 670 // fetch file preview when not submitted yet, like in online contribution Confirm and ThankYou page
c2292dbd 671 $viewOnlyFileValues = empty($profileContactType) ? array() : array($profileContactType => array());
6a488035
TO
672 foreach ($fields as $key => $field) {
673 if ($viewOnly &&
674 isset($field['data_type']) &&
675 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
676 ) {
c2292dbd 677 //retrieve file value from submitted values on basis of $profileContactType
9b7bedc5 678 $fileValue = CRM_Utils_Array::value($key, $this->_params);
679 if (!empty($profileContactType) && !empty($this->_params[$profileContactType])) {
680 $fileValue = CRM_Utils_Array::value($key, $this->_params[$profileContactType]);
681 }
c2292dbd 682
683 if ($fileValue) {
684 $path = CRM_Utils_Array::value('name', $fileValue);
685 $fileType = CRM_Utils_Array::value('type', $fileValue);
686 $fileValue = CRM_Utils_File::getFileURL($path, $fileType);
f3726153 687 }
6a488035 688
c2292dbd 689 // format custom file value fetched from submitted value
690 if ($profileContactType) {
691 $viewOnlyFileValues[$profileContactType][$key] = $fileValue;
692 }
693 else {
694 $viewOnlyFileValues[$key] = $fileValue;
695 }
1aedfc98 696
697 // On viewOnly use-case (as in online contribution Confirm page) we no longer need to set
698 // required property because being required file is already uploaded while registration
699 $field['is_required'] = FALSE;
c2292dbd 700 }
133e2c99 701 if ($profileContactType) {
702 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
c043358f 703 if ($profileContactType == 'honor') {
704 $honoreeNamefields = array(
705 'prefix_id',
706 'first_name',
707 'last_name',
708 'suffix_id',
709 'organization_name',
710 'household_name',
711 );
712 if (in_array($field['name'], $honoreeNamefields)) {
713 unset($fields[$field['name']]);
714 continue;
715 }
133e2c99 716 }
6a488035
TO
717 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
718 CRM_Core_BAO_UFGroup::buildProfile(
719 $this,
720 $field,
721 CRM_Profile_Form::MODE_CREATE,
722 $contactID,
133e2c99 723 TRUE,
724 $profileContactType
6a488035 725 );
133e2c99 726 $this->_fields[$profileContactType][$key] = $field;
6a488035
TO
727 }
728 else {
729 unset($fields[$key]);
730 }
731 }
732 else {
733 CRM_Core_BAO_UFGroup::buildProfile(
734 $this,
735 $field,
736 CRM_Profile_Form::MODE_CREATE,
737 $contactID,
738 TRUE
739 );
740 $this->_fields[$key] = $field;
741 }
71fc6ea4
DG
742 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
743 if ($field['add_captcha'] && !$this->_userID) {
6a488035
TO
744 $addCaptcha = TRUE;
745 }
746 }
747
748 $this->assign($name, $fields);
749
6d43e496 750 if ($profileContactType && count($viewOnlyFileValues[$profileContactType])) {
751 $this->assign('viewOnlyPrefixFileValues', $viewOnlyFileValues);
752 }
753 elseif (count($viewOnlyFileValues)) {
f3726153 754 $this->assign('viewOnlyFileValues', $viewOnlyFileValues);
755 }
756
6a488035
TO
757 if ($addCaptcha && !$viewOnly) {
758 $captcha = CRM_Utils_ReCAPTCHA::singleton();
759 $captcha->add($this);
760 $this->assign('isCaptcha', TRUE);
761 }
762 }
763 }
764 }
765
4779abb3 766 /**
767 * Add onbehalf/honoree profile fields and native module fields.
768 *
769 * @param int $id
770 * @param CRM_Core_Form $form
771 */
bcb8cc84 772 public function buildComponentForm($id, $form) {
773 if (empty($id)) {
774 return;
775 }
776
777 $contactID = $this->getContactID();
778
779 foreach (array('soft_credit', 'on_behalf') as $module) {
bcb8cc84 780 if ($module == 'soft_credit') {
4779abb3 781 if (empty($form->_values['honoree_profile_id'])) {
782 continue;
783 }
bcb8cc84 784
4779abb3 785 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['honoree_profile_id'], 'is_active')) {
bcb8cc84 786 CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of honoree and the selected honoree profile is either disabled or not found.'));
787 }
788
4779abb3 789 $profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']);
bcb8cc84 790 $requiredProfileFields = array(
791 'Individual' => array('first_name', 'last_name'),
792 'Organization' => array('organization_name', 'email'),
793 'Household' => array('household_name', 'email'),
794 );
4779abb3 795 $validProfile = CRM_Core_BAO_UFGroup::checkValidProfile($form->_values['honoree_profile_id'], $requiredProfileFields[$profileContactType]);
bcb8cc84 796 if (!$validProfile) {
797 CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of honoree and the required fields of the selected honoree profile are disabled or doesn\'t exist.'));
798 }
799
cb804cd9 800 foreach (array('honor_block_title', 'honor_block_text') as $name) {
4779abb3 801 $form->assign($name, $form->_values[$name]);
cb804cd9 802 }
803
804 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
805
806 // radio button for Honor Type
4779abb3 807 foreach ($form->_values['soft_credit_types'] as $value) {
cb804cd9 808 $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value);
809 }
810 $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE);
811
4779abb3 812 $honoreeProfileFields = CRM_Core_BAO_UFGroup::getFields(
813 $this->_values['honoree_profile_id'], FALSE,
814 NULL, NULL,
815 NULL, FALSE,
816 NULL, TRUE,
817 NULL, CRM_Core_Permission::CREATE
cb804cd9 818 );
cb804cd9 819 $form->assign('honoreeProfileFields', $honoreeProfileFields);
820
821 // add the form elements
822 foreach ($honoreeProfileFields as $name => $field) {
823 // If soft credit type is not chosen then make omit requiredness from honoree profile fields
824 if (count($form->_submitValues) &&
825 empty($form->_submitValues['soft_credit_type_id']) &&
826 !empty($field['is_required'])
827 ) {
828 $field['is_required'] = FALSE;
829 }
c043358f 830 CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, NULL, FALSE, FALSE, NULL, 'honor');
cb804cd9 831 }
bcb8cc84 832 }
833 else {
4779abb3 834 if (empty($form->_values['onbehalf_profile_id'])) {
835 continue;
836 }
bcb8cc84 837
4779abb3 838 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['onbehalf_profile_id'], 'is_active')) {
bcb8cc84 839 CRM_Core_Error::fatal(ts('This contribution page has been configured for contribution on behalf of an organization and the selected onbehalf profile is either disabled or not found.'));
840 }
841
842 $member = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
843 if (empty($member['is_active'])) {
844 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
4779abb3 845 $onBehalfProfile = CRM_Core_BAO_UFGroup::profileGroups($form->_values['onbehalf_profile_id']);
0c7c9ff7
KC
846 foreach (
847 array(
bcb8cc84 848 'Individual',
849 'Organization',
850 'Household',
0c7c9ff7
KC
851 ) as $contactType
852 ) {
bcb8cc84 853 if (in_array($contactType, $onBehalfProfile) &&
854 (in_array('Membership', $onBehalfProfile) ||
855 in_array('Contribution', $onBehalfProfile)
856 )
857 ) {
858 CRM_Core_Error::fatal($msg);
859 }
860 }
861 }
862
c043358f 863 if ($contactID) {
33260076 864 // retrieve all permissioned organizations of contact $contactID
865 $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($contactID, NULL, NULL, 'Organization');
c043358f 866
33260076 867 if (count($organizations)) {
c043358f 868 // Related org url - pass checksum if needed
f23093b2 869 $args = array(
4779abb3 870 'ufId' => $form->_values['onbehalf_profile_id'],
f23093b2 871 'cid' => '',
872 );
c043358f 873 if (!empty($_GET['cs'])) {
874 $args = array(
4779abb3 875 'ufId' => $form->_values['onbehalf_profile_id'],
c043358f 876 'uid' => $this->_contactID,
877 'cs' => $_GET['cs'],
878 'cid' => '',
879 );
880 }
881 $locDataURL = CRM_Utils_System::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
882 $form->assign('locDataURL', $locDataURL);
883 }
33260076 884 if (count($organizations) > 0) {
885 $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $organizations));
c043358f 886
887 $orgOptions = array(
888 0 => ts('Select an existing organization'),
889 1 => ts('Enter a new organization'),
890 );
891 $form->addRadio('org_option', ts('options'), $orgOptions);
892 $form->setDefaults(array('org_option' => 0));
893 }
bcb8cc84 894 }
895
c043358f 896 $form->assign('fieldSetTitle', ts('Organization Details'));
c043358f 897
4779abb3 898 if (CRM_Utils_Array::value('is_for_organization', $form->_values)) {
899 if ($form->_values['is_for_organization'] == 2) {
c043358f 900 $form->assign('onBehalfRequired', TRUE);
bcb8cc84 901 }
902 else {
903 $form->addElement('checkbox', 'is_for_organization',
904 $form->_values['for_organization'],
905 NULL
906 );
907 }
908 }
c043358f 909
4779abb3 910 $profileFields = CRM_Core_BAO_UFGroup::getFields(
911 $form->_values['onbehalf_profile_id'],
912 FALSE, CRM_Core_Action::VIEW, NULL,
913 NULL, FALSE, NULL, FALSE, NULL,
914 CRM_Core_Permission::CREATE, NULL
c043358f 915 );
4779abb3 916
c043358f 917 $form->assign('onBehalfOfFields', $profileFields);
918 if (!empty($form->_submitValues['onbehalf'])) {
919 if (!empty($form->_submitValues['onbehalfof_id'])) {
920 $form->assign('submittedOnBehalf', $form->_submitValues['onbehalfof_id']);
921 }
922 $form->assign('submittedOnBehalfInfo', json_encode($form->_submitValues['onbehalf']));
923 }
924
925 $fieldTypes = array('Contact', 'Organization');
926 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
927 $fieldTypes = array_merge($fieldTypes, $contactSubType);
928
929 foreach ($profileFields as $name => $field) {
930 if (in_array($field['field_type'], $fieldTypes)) {
931 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
932 if (in_array($prefixName, array('organization_name', 'email')) && empty($field['is_required'])) {
933 $field['is_required'] = 1;
934 }
935 if (count($form->_submitValues) &&
936 empty($form->_submitValues['is_for_organization']) &&
4779abb3 937 $form->_values['is_for_organization'] == 1 &&
c043358f 938 !empty($field['is_required'])
939 ) {
940 $field['is_required'] = FALSE;
941 }
4779abb3 942 CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf');
c043358f 943 }
944 }
bcb8cc84 945 }
946 }
947
948 }
949
f4aaa82a 950 /**
fe482240 951 * Check template file exists.
f92d1e2a
EM
952 *
953 * @param string $suffix
f4aaa82a
EM
954 *
955 * @return null|string
956 */
00be9182 957 public function checkTemplateFileExists($suffix = NULL) {
6a488035
TO
958 if ($this->_id) {
959 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
960 $template = CRM_Core_Form::getTemplate();
961 if ($template->template_exists($templateFile)) {
962 return $templateFile;
963 }
964 }
965 return NULL;
966 }
967
186c9c17 968 /**
fe482240 969 * Use the form name to create the tpl file name.
186c9c17
EM
970 *
971 * @return string
186c9c17 972 */
00be9182 973 public function getTemplateFileName() {
6a488035
TO
974 $fileName = $this->checkTemplateFileExists();
975 return $fileName ? $fileName : parent::getTemplateFileName();
976 }
977
186c9c17 978 /**
f92d1e2a
EM
979 * Add the extra.tpl in.
980 *
186c9c17 981 * Default extra tpl file basically just replaces .tpl with .extra.tpl
f92d1e2a 982 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
186c9c17
EM
983 *
984 * @return string
186c9c17 985 */
00be9182 986 public function overrideExtraTemplateFileName() {
6a488035
TO
987 $fileName = $this->checkTemplateFileExists('extra.');
988 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
989 }
990
991 /**
100fef9d 992 * Authenticate pledge user during online payment.
6a488035
TO
993 */
994 public function authenticatePledgeUser() {
995 //get the userChecksum and contact id
996 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
997 $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
998
999 //get pledge status and contact id
353ffa53
TO
1000 $pledgeValues = array();
1001 $pledgeParams = array('id' => $this->_values['pledge_id']);
6a488035
TO
1002 $returnProperties = array('contact_id', 'status_id');
1003 CRM_Core_DAO::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
1004
1005 //get all status
1006 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
353ffa53
TO
1007 $validStatus = array(
1008 array_search('Pending', $allStatus),
6a488035
TO
1009 array_search('In Progress', $allStatus),
1010 array_search('Overdue', $allStatus),
1011 );
1012
1013 $validUser = FALSE;
1014 if ($this->_userID &&
1015 $this->_userID == $pledgeValues['contact_id']
1016 ) {
1017 //check for authenticated user.
1018 $validUser = TRUE;
1019 }
1020 elseif ($userChecksum && $pledgeValues['contact_id']) {
1021 //check for anonymous user.
1022 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($pledgeValues['contact_id'], $userChecksum);
1023
1024 //make sure cid is same as pledge contact id
1025 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
1026 $validUser = FALSE;
1027 }
1028 }
1029
1030 if (!$validUser) {
1031 CRM_Core_Error::fatal(ts("Oops. It looks like you have an incorrect or incomplete link (URL). Please make sure you've copied the entire link, and try again. Contact the site administrator if this error persists."));
1032 }
1033
1034 //check for valid pledge status.
1035 if (!in_array($pledgeValues['status_id'], $validStatus)) {
1036 CRM_Core_Error::fatal(ts('Oops. You cannot make a payment for this pledge - pledge status is %1.', array(1 => CRM_Utils_Array::value($pledgeValues['status_id'], $allStatus))));
1037 }
1038 }
1039
1040 /**
f92d1e2a
EM
1041 * Cancel recurring contributions.
1042 *
6a488035
TO
1043 * In case user cancel recurring contribution,
1044 * When we get the control back from payment gate way
1045 * lets delete the recurring and related contribution.
389bcebf 1046 */
6a488035 1047 public function cancelRecurring() {
a3d827a7 1048 $isCancel = CRM_Utils_Request::retrieve('cancel', 'Boolean');
6a488035 1049 if ($isCancel) {
a3d827a7
CW
1050 $isRecur = CRM_Utils_Request::retrieve('isRecur', 'Boolean');
1051 $recurId = CRM_Utils_Request::retrieve('recurId', 'Positive');
6a488035
TO
1052 //clean db for recurring contribution.
1053 if ($isRecur && $recurId) {
1054 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($recurId);
1055 }
a3d827a7 1056 $contribId = CRM_Utils_Request::retrieve('contribId', 'Positive');
6a488035
TO
1057 if ($contribId) {
1058 CRM_Contribute_BAO_Contribution::deleteContribution($contribId);
1059 }
1060 }
1061 }
96025800 1062
42e3a033
EM
1063 /**
1064 * Build Membership Block in Contribution Pages.
1065 *
42e3a033
EM
1066 * @param int $cid
1067 * Contact checked for having a current membership for a particular membership.
a46bfec1
EM
1068 * @param bool $isContributionMainPage
1069 * Is this the main page? If so add form input fields.
1070 * (or better yet don't have this functionality in a function shared with forms that don't share it).
42e3a033
EM
1071 * @param int $selectedMembershipTypeID
1072 * Selected membership id.
1073 * @param bool $thankPage
1074 * Thank you page.
1075 * @param null $isTest
1076 *
1077 * @return bool
1078 * Is this a separate membership payment
1079 */
1080 protected function buildMembershipBlock(
1081 $cid,
a46bfec1 1082 $isContributionMainPage = FALSE,
42e3a033
EM
1083 $selectedMembershipTypeID = NULL,
1084 $thankPage = FALSE,
1085 $isTest = NULL
1086 ) {
1087
1088 $separateMembershipPayment = FALSE;
1089 if ($this->_membershipBlock) {
1090 $this->_currentMemberships = array();
1091
42e3a033
EM
1092 $membershipTypeIds = $membershipTypes = $radio = array();
1093 $membershipPriceset = (!empty($this->_priceSetId) && $this->_useForMember) ? TRUE : FALSE;
1094
1095 $allowAutoRenewMembership = $autoRenewOption = FALSE;
1096 $autoRenewMembershipTypeOptions = array();
1097
a46bfec1 1098 $separateMembershipPayment = CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock);
42e3a033
EM
1099
1100 if ($membershipPriceset) {
1101 foreach ($this->_priceSet['fields'] as $pField) {
1102 if (empty($pField['options'])) {
1103 continue;
1104 }
1105 foreach ($pField['options'] as $opId => $opValues) {
1106 if (empty($opValues['membership_type_id'])) {
1107 continue;
1108 }
1109 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
1110 }
1111 }
1112 }
a46bfec1
EM
1113 elseif (!empty($this->_membershipBlock['membership_types'])) {
1114 $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
42e3a033
EM
1115 }
1116
1117 if (!empty($membershipTypeIds)) {
1118 //set status message if wrong membershipType is included in membershipBlock
1119 if (isset($this->_mid) && !$membershipPriceset) {
1120 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
1121 $this->_mid,
1122 'membership_type_id'
1123 );
1124 if (!in_array($membershipTypeID, $membershipTypeIds)) {
1125 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
1126 }
1127 }
1128
4c7b8a7d 1129 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
42e3a033
EM
1130 $this->_membershipTypeValues = $membershipTypeValues;
1131 $endDate = NULL;
1132 foreach ($membershipTypeIds as $value) {
1133 $memType = $membershipTypeValues[$value];
1134 if ($selectedMembershipTypeID != NULL) {
1135 if ($memType['id'] == $selectedMembershipTypeID) {
1136 $this->assign('minimum_fee',
1137 CRM_Utils_Array::value('minimum_fee', $memType)
1138 );
1139 $this->assign('membership_name', $memType['name']);
1140 if (!$thankPage && $cid) {
1141 $membership = new CRM_Member_DAO_Membership();
1142 $membership->contact_id = $cid;
1143 $membership->membership_type_id = $memType['id'];
1144 if ($membership->find(TRUE)) {
1145 $this->assign('renewal_mode', TRUE);
1146 $memType['current_membership'] = $membership->end_date;
1147 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
1148 }
1149 }
1150 $membershipTypes[] = $memType;
1151 }
1152 }
1153 elseif ($memType['is_active']) {
1154 $javascriptMethod = NULL;
08a4ce4e 1155 $allowAutoRenewOpt = (int) $memType['auto_renew'];
42e3a033
EM
1156 if (is_array($this->_paymentProcessors)) {
1157 foreach ($this->_paymentProcessors as $id => $val) {
fb357d6e 1158 if ($id && !$val['is_recur']) {
42e3a033
EM
1159 $allowAutoRenewOpt = 0;
1160 continue;
1161 }
1162 }
1163 }
1164
1165 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
1166 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array::value($value, CRM_Utils_Array::value('auto_renew', $this->_membershipBlock));;
1167
1168 if ($allowAutoRenewOpt) {
1169 $allowAutoRenewMembership = TRUE;
1170 }
1171
1172 //add membership type.
1173 $radio[$memType['id']] = $this->createElement('radio', NULL, NULL, NULL,
1174 $memType['id'], $javascriptMethod
1175 );
1176 if ($cid) {
1177 $membership = new CRM_Member_DAO_Membership();
1178 $membership->contact_id = $cid;
1179 $membership->membership_type_id = $memType['id'];
1180
1181 //show current membership, skip pending and cancelled membership records,
1182 //because we take first membership record id for renewal
1183 $membership->whereAdd('status_id != 5 AND status_id !=6');
1184
1185 if (!is_null($isTest)) {
1186 $membership->is_test = $isTest;
1187 }
1188
1189 //CRM-4297
1190 $membership->orderBy('end_date DESC');
1191
1192 if ($membership->find(TRUE)) {
1193 if (!$membership->end_date) {
1194 unset($radio[$memType['id']]);
1195 $this->assign('islifetime', TRUE);
1196 continue;
1197 }
1198 $this->assign('renewal_mode', TRUE);
1199 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
1200 $memType['current_membership'] = $membership->end_date;
1201 if (!$endDate) {
1202 $endDate = $memType['current_membership'];
1203 $this->_defaultMemTypeId = $memType['id'];
1204 }
1205 if ($memType['current_membership'] < $endDate) {
1206 $endDate = $memType['current_membership'];
1207 $this->_defaultMemTypeId = $memType['id'];
1208 }
1209 }
1210 }
1211 $membershipTypes[] = $memType;
1212 }
1213 }
1214 }
1215
a46bfec1
EM
1216 $this->assign('membershipBlock', $this->_membershipBlock);
1217 $this->assign('showRadio', $isContributionMainPage);
1218 $this->assign('membershipTypes', $membershipTypes);
1219 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
1220 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
1221 //give preference to user submitted auto_renew value.
1222 $takeUserSubmittedAutoRenew = (!empty($_POST) || $this->isSubmitted()) ? TRUE : FALSE;
1223 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
1224
c843169c
MW
1225 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
1226 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId);
1227 if (isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
1228 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
1229 }
1230 else {
1231 $this->assign('autoRenewOption', $autoRenewOption);
1232 }
1233
a46bfec1 1234 if ($isContributionMainPage) {
42e3a033 1235 if (!$membershipPriceset) {
a46bfec1 1236 if (!$this->_membershipBlock['is_required']) {
42e3a033
EM
1237 $this->assign('showRadioNoThanks', TRUE);
1238 $radio[''] = $this->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
1239 $this->addGroup($radio, 'selectMembership', NULL);
1240 }
a46bfec1 1241 elseif ($this->_membershipBlock['is_required'] && count($radio) == 1) {
42e3a033
EM
1242 $temp = array_keys($radio);
1243 $this->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
1244 $this->assign('singleMembership', TRUE);
1245 $this->assign('showRadio', FALSE);
1246 }
1247 else {
1248 $this->addGroup($radio, 'selectMembership', NULL);
1249 }
1250
1251 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
1252 }
42e3a033 1253
fb357d6e 1254 if ((!$this->_values['is_pay_later'] || is_array($this->_paymentProcessors)) && ($allowAutoRenewMembership || $autoRenewOption)) {
c843169c
MW
1255 if ($autoRenewOption == 2) {
1256 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
1257 }
1258 else {
1259 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
1260 }
42e3a033
EM
1261 }
1262
1263 }
42e3a033
EM
1264 }
1265
1266 return $separateMembershipPayment;
1267 }
1268
90102a32
EM
1269 /**
1270 * Determine if recurring parameters need to be added to the form parameters.
8cb12ff1 1271 *
90102a32
EM
1272 * - is_recur
1273 * - frequency_interval
1274 * - frequency_unit
1275 *
1276 * For membership this is based on the membership type.
1277 *
1278 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1279 *
1280 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1281 */
1282 protected function setRecurringMembershipParams() {
8cb12ff1 1283 $selectedMembershipTypeID = CRM_Utils_Array::value('selectMembership', $this->_params);
1284 if ($selectedMembershipTypeID) {
fd359255
EM
1285 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1286 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1287 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1288 // this with an else (calculate for price set).
8cb12ff1 1289 $membershipTypes = CRM_Price_BAO_PriceSet::getMembershipTypesFromPriceSet($this->_priceSetId);
1290 if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required'])
1291 || (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) &&
1292 !empty($this->_params['is_recur']))
1293 ) {
fd359255
EM
1294 $this->_params['auto_renew'] = TRUE;
1295 }
1296 }
8cb12ff1 1297 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId']))
1298 && !empty($this->_paymentProcessor['is_recur']) &&
1299 CRM_Utils_Array::value('auto_renew', $this->_params)
1300 && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])
90102a32
EM
1301 ) {
1302
1303 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
1304 // check if price set is not quick config
1305 if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
1306 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
1307 }
1308 else {
1309 // FIXME: set interval and unit based on selected membership type
1310 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1311 $this->_params['selectMembership'], 'duration_interval'
1312 );
1313 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1314 $this->_params['selectMembership'], 'duration_unit'
1315 );
1316 }
1317 }
1318 }
1319
6a488035 1320}