CRM-16808 paypal express follow up fixes
[civicrm-core.git] / CRM / Contribute / Form / ContributionBase.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33
e3155fe2
EM
34use Civi\Payment\System;
35
6a488035 36/**
f92d1e2a 37 * This class generates form components for processing a contribution.
6a488035
TO
38 */
39class CRM_Contribute_Form_ContributionBase extends CRM_Core_Form {
40
41 /**
f92d1e2a 42 * The id of the contribution page that we are processing.
6a488035
TO
43 *
44 * @var int
6a488035
TO
45 */
46 public $_id;
47
48 /**
100fef9d 49 * The mode that we are in
6a488035
TO
50 *
51 * @var string
52 * @protect
53 */
54 public $_mode;
55
56 /**
100fef9d 57 * The contact id related to a membership
6a488035
TO
58 *
59 * @var int
6a488035
TO
60 */
61 public $_membershipContactID;
62
63 /**
100fef9d 64 * The values for the contribution db object
6a488035
TO
65 *
66 * @var array
6a488035
TO
67 */
68 public $_values;
69
70 /**
100fef9d 71 * The paymentProcessor attributes for this page
6a488035
TO
72 *
73 * @var array
6a488035
TO
74 */
75 public $_paymentProcessor;
1b9f9ca3 76
6a488035
TO
77 public $_paymentObject = NULL;
78
79 /**
80 * The membership block for this page
81 *
82 * @var array
6a488035
TO
83 */
84 public $_membershipBlock = NULL;
85
f64a217a
EM
86 /**
87 * Does this form support a separate membership payment
88 * @var bool
89 */
90 protected $_separateMembershipPayment;
6a488035
TO
91
92 /**
93 * The params submitted by the form and computed by the app
94 *
95 * @var array
6a488035 96 */
90102a32 97 public $_params = array();
6a488035
TO
98
99 /**
100 * The fields involved in this contribution page
101 *
102 * @var array
6a488035 103 */
532ee86f 104 public $_fields = array();
6a488035
TO
105
106 /**
f92d1e2a 107 * The billing location id for this contribution page.
6a488035
TO
108 *
109 * @var int
6a488035
TO
110 */
111 public $_bltID;
112
113 /**
114 * Cache the amount to make things easier
115 *
116 * @var float
6a488035
TO
117 */
118 public $_amount;
119
120 /**
100fef9d 121 * Pcp id
6a488035
TO
122 *
123 * @var integer
6a488035
TO
124 */
125 public $_pcpId;
126
127 /**
100fef9d 128 * Pcp block
6a488035
TO
129 *
130 * @var array
6a488035
TO
131 */
132 public $_pcpBlock;
133
134 /**
100fef9d 135 * Pcp info
6a488035
TO
136 *
137 * @var array
6a488035
TO
138 */
139 public $_pcpInfo;
140
5b757295 141 /**
142 * The contact id of the person for whom membership is being added or renewed based on the cid in the url,
143 * checksum, or session
0e5e0c2e 144 * @var int
5b757295 145 */
0e5e0c2e 146 public $_contactID;
5b757295 147
6a488035
TO
148 protected $_userID;
149
150 /**
100fef9d 151 * The Membership ID for membership renewal
6a488035
TO
152 *
153 * @var int
6a488035
TO
154 */
155 public $_membershipId;
156
157 /**
158 * Price Set ID, if the new price set method is used
159 *
160 * @var int
6a488035
TO
161 */
162 public $_priceSetId;
163
164 /**
165 * Array of fields for the price set
166 *
167 * @var array
6a488035
TO
168 */
169 public $_priceSet;
170
171 public $_action;
172
874c9be7 173 /**
353ffa53
TO
174 * Is honor block is enabled for this contribution?
175 *
176 * @var boolean
177 */
8af73472 178 public $_honor_block_is_active = FALSE;
179
dbddfb08
EM
180 /**
181 * Contribution mode e.g express for payment express, notify for off-site + notification back to CiviCRM
182 * @var string
183 */
184 public $_contributeMode;
185
186 /**
100fef9d 187 * Contribution page supports memberships
dbddfb08
EM
188 * @var boolean
189 */
190 public $_useForMember;
8ae4d0d3 191
192 public $_isBillingAddressRequiredForPayLater;
353ffa53 193
6a488035 194 /**
fe482240 195 * Set variables up before form is built.
6a488035 196 *
7fe37828
EM
197 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
198 * @throws \Exception
6a488035
TO
199 */
200 public function preProcess() {
6a488035
TO
201
202 // current contribution page id
203 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
204 if (!$this->_id) {
d420cf02
DL
205 // seems like the session is corrupted and/or we lost the id trail
206 // lets just bump this to a regular session error and redirect user to main page
207 $this->controller->invalidKeyRedirect();
6a488035 208 }
d420cf02 209
5b757295 210 // this was used prior to the cleverer this_>getContactID - unsure now
a6c15c46 211 $this->_userID = CRM_Core_Session::singleton()->get('userID');
5b757295 212
8af73472 213 //Check if honor block is enabled for current contribution
bc0e993a 214 $ufJoinParams = array(
215 'module' => 'soft_credit',
216 'entity_table' => 'civicrm_contribution_page',
217 'entity_id' => $this->_id,
218 );
219 $ufJoin = new CRM_Core_DAO_UFJoin();
220 $ufJoin->copyValues($ufJoinParams);
221 $ufJoin->find(TRUE);
222 $this->_honor_block_is_active = $ufJoin->is_active;
8af73472 223
5b757295 224 $this->_contactID = $this->_membershipContactID = $this->getContactID();
6a488035 225 $this->_mid = NULL;
5b757295 226 if ($this->_contactID) {
6a488035
TO
227 $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
228 if ($this->_mid) {
229 $membership = new CRM_Member_DAO_Membership();
230 $membership->id = $this->_mid;
231
232 if ($membership->find(TRUE)) {
233 $this->_defaultMemTypeId = $membership->membership_type_id;
5b757295 234 if ($membership->contact_id != $this->_contactID) {
6fe8deba 235 $validMembership = FALSE;
6a488035 236 $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID);
6fe8deba
DS
237 if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) {
238 $this->_membershipContactID = $membership->contact_id;
239 $this->assign('membershipContactID', $this->_membershipContactID);
240 $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']);
241 $validMembership = TRUE;
0db6c3e1
TO
242 }
243 else {
51e89def
DS
244 $membershipType = new CRM_Member_BAO_MembershipType();
245 $membershipType->id = $membership->membership_type_id;
246 if ($membershipType->find(TRUE)) {
f9f0eff9 247 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
f92d1e2a 248 // Convert to comma separated list.
f9f0eff9 249 $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
51e89def
DS
250 $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
251 if (array_key_exists($membership->contact_id, $permContacts)) {
252 $this->_membershipContactID = $membership->contact_id;
6fe8deba 253 $validMembership = TRUE;
51e89def
DS
254 }
255 }
6a488035 256 }
6fe8deba
DS
257 if (!$validMembership) {
258 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');
259 }
6a488035
TO
260 }
261 }
262 else {
263 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');
264 }
265 unset($membership);
266 }
267 }
268
269 // we do not want to display recently viewed items, so turn off
270 $this->assign('displayRecent', FALSE);
271 // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
272 // Use Browser Print instead.
273 $this->assign('browserPrint', TRUE);
274
275 // action
276 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
277 $this->assign('action', $this->_action);
278
279 // current mode
280 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
281
282 $this->_values = $this->get('values');
283 $this->_fields = $this->get('fields');
284 $this->_bltID = $this->get('bltID');
285 $this->_paymentProcessor = $this->get('paymentProcessor');
286 $this->_priceSetId = $this->get('priceSetId');
287 $this->_priceSet = $this->get('priceSet');
288
289 if (!$this->_values) {
290 // get all the values from the dao object
291 $this->_values = array();
292 $this->_fields = array();
293
294 CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
295
a7488080 296 if (empty($this->_values['is_active'])) {
4b57bc9f 297 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id);
6a488035
TO
298 }
299
8345c9d3 300 $this->assignBillingType();
6a488035
TO
301
302 // check for is_monetary status
303 $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values);
304 $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values);
305
6a488035 306 if ($isMonetary &&
8cc574cf 307 (!$isPayLater || !empty($this->_values['payment_processor']))
6a488035 308 ) {
a6c15c46
EM
309 $this->_paymentProcessorIDs = explode(
310 CRM_Core_DAO::VALUE_SEPARATOR,
311 CRM_Utils_Array::value('payment_processor', $this->_values)
1b9f9ca3 312 );
f92d1e2a 313
1b9f9ca3 314 $this->assignPaymentProcessor();
6a488035
TO
315 }
316
317 // get price info
318 // CRM-5095
9da8dc8c 319 CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page');
6a488035
TO
320
321 // this avoids getting E_NOTICE errors in php
322 $setNullFields = array(
323 'amount_block_is_active',
6a488035
TO
324 'is_allow_other_amount',
325 'footer_text',
326 );
327 foreach ($setNullFields as $f) {
328 if (!isset($this->_values[$f])) {
329 $this->_values[$f] = NULL;
330 }
331 }
332
333 //check if Membership Block is enabled, if Membership Fields are included in profile
334 //get membership section for this contribution page
335 $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
336 $this->set('membershipBlock', $this->_membershipBlock);
337
338 if ($this->_values['custom_pre_id']) {
339 $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
340 }
341
342 if ($this->_values['custom_post_id']) {
343 $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
344 }
345
346 if (((isset($postProfileType) && $postProfileType == 'Membership') ||
347 (isset($preProfileType) && $preProfileType == 'Membership')
348 ) &&
349 !$this->_membershipBlock['is_active']
350 ) {
351 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.'));
352 }
353
354 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
355
356 if ($pledgeBlock) {
357 $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock);
358 $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock);
359 $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock);
360 $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock);
361
362 //set pledge id in values
363 $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
364
365 //authenticate pledge user for pledge payment.
366 if ($pledgeId) {
367 $this->_values['pledge_id'] = $pledgeId;
368
369 //lets override w/ pledge campaign.
370 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
371 $pledgeId,
372 'campaign_id'
373 );
374 self::authenticatePledgeUser();
375 }
376 }
377 $this->set('values', $this->_values);
378 $this->set('fields', $this->_fields);
379 }
380
381 // Handle PCP
382 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
383 if ($pcpId) {
353ffa53
TO
384 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
385 $this->_pcpId = $pcp['pcpId'];
6a488035 386 $this->_pcpBlock = $pcp['pcpBlock'];
353ffa53 387 $this->_pcpInfo = $pcp['pcpInfo'];
6a488035
TO
388 }
389
390 // Link (button) for users to create their own Personal Campaign page
391 if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
392 $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign',
393 "action=add&reset=1&pageId={$this->_id}&component=contribute",
394 FALSE, NULL, TRUE
395 );
396 $this->assign('linkTextUrl', $linkTextUrl);
397 $this->assign('linkText', $linkText);
398 }
399
400 //set pledge block if block id is set
a7488080 401 if (!empty($this->_values['pledge_block_id'])) {
6a488035
TO
402 $this->assign('pledgeBlock', TRUE);
403 }
404
f92d1e2a 405 // check if one of the (amount , membership) blocks is active or not.
6a488035
TO
406 $this->_membershipBlock = $this->get('membershipBlock');
407
408 if (!$this->_values['amount_block_is_active'] &&
409 !$this->_membershipBlock['is_active'] &&
410 !$this->_priceSetId
411 ) {
412 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.'));
413 }
414
415 if ($this->_values['amount_block_is_active']) {
416 $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
417 }
418
419 $this->_contributeMode = $this->get('contributeMode');
420 $this->assign('contributeMode', $this->_contributeMode);
421
422 //assigning is_monetary and is_email_receipt to template
423 $this->assign('is_monetary', $this->_values['is_monetary']);
424 $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
425 $this->assign('bltID', $this->_bltID);
426
427 //assign cancelSubscription URL to templates
428 $this->assign('cancelSubscriptionUrl',
429 CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)
430 );
431
432 // assigning title to template in case someone wants to use it, also setting CMS page title
433 if ($this->_pcpId) {
434 $this->assign('title', $this->_pcpInfo['title']);
435 CRM_Utils_System::setTitle($this->_pcpInfo['title']);
436 }
437 else {
438 $this->assign('title', $this->_values['title']);
439 CRM_Utils_System::setTitle($this->_values['title']);
440 }
441 $this->_defaults = array();
442
443 $this->_amount = $this->get('amount');
444
445 //CRM-6907
446 $config = CRM_Core_Config::singleton();
447 $config->defaultCurrency = CRM_Utils_Array::value('currency',
448 $this->_values,
449 $config->defaultCurrency
450 );
451
452 //lets allow user to override campaign.
453 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
454 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
455 $this->_values['campaign_id'] = $campID;
456 }
457
458 //do check for cancel recurring and clean db, CRM-7696
459 if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) {
460 self::cancelRecurring();
461 }
8ae4d0d3 462
463 // check if billing block is required for pay later
464 if (CRM_Utils_Array::value('is_pay_later', $this->_values)) {
465 $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values);
466 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
467 }
6a488035
TO
468 }
469
470 /**
fe482240 471 * Set the default values.
6a488035 472 */
00be9182 473 public function setDefaultValues() {
6a488035
TO
474 return $this->_defaults;
475 }
476
477 /**
fe482240 478 * Assign the minimal set of variables to the template.
6a488035 479 */
00be9182 480 public function assignToTemplate() {
6a488035 481 $name = CRM_Utils_Array::value('billing_first_name', $this->_params);
a7488080 482 if (!empty($this->_params['billing_middle_name'])) {
6a488035
TO
483 $name .= " {$this->_params['billing_middle_name']}";
484 }
485 $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
486 $name = trim($name);
487 $this->assign('billingName', $name);
488 $this->set('name', $name);
489
490 $this->assign('paymentProcessor', $this->_paymentProcessor);
491 $vars = array(
353ffa53
TO
492 'amount',
493 'currencyID',
494 'credit_card_type',
495 'trxn_id',
496 'amount_level',
6a488035
TO
497 );
498
499 $config = CRM_Core_Config::singleton();
8cc574cf 500 if (isset($this->_values['is_recur']) && !empty($this->_paymentProcessor['is_recur'])) {
6a488035
TO
501 $this->assign('is_recur_enabled', 1);
502 $vars = array_merge($vars, array(
353ffa53
TO
503 'is_recur',
504 'frequency_interval',
505 'frequency_unit',
506 'installments',
507 ));
6a488035
TO
508 }
509
510 if (in_array('CiviPledge', $config->enableComponents) &&
511 CRM_Utils_Array::value('is_pledge', $this->_params) == 1
512 ) {
513 $this->assign('pledge_enabled', 1);
514
515 $vars = array_merge($vars, array(
516 'is_pledge',
353ffa53
TO
517 'pledge_frequency_interval',
518 'pledge_frequency_unit',
519 'pledge_installments',
520 ));
6a488035
TO
521 }
522
523 if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
524 $this->_params['amount_level'] = '';
525 }
526
527 foreach ($vars as $v) {
3fb990f4 528 if (isset($this->_params[$v])) {
735fe42d
PJ
529 if ($v == "amount" && $this->_params[$v] === 0) {
530 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
3fb990f4 531 }
6a488035
TO
532 $this->assign($v, $this->_params[$v]);
533 }
534 }
535
536 // assign the address formatted up for display
537 $addressParts = array(
538 "street_address-{$this->_bltID}",
539 "city-{$this->_bltID}",
540 "postal_code-{$this->_bltID}",
541 "state_province-{$this->_bltID}",
542 "country-{$this->_bltID}",
543 );
544
545 $addressFields = array();
546 foreach ($addressParts as $part) {
547 list($n, $id) = explode('-', $part);
548 $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $this->_params);
549 }
550
551 $this->assign('address', CRM_Utils_Address::format($addressFields));
552
a7488080 553 if (!empty($this->_params['hidden_onbehalf_profile'])) {
6a488035
TO
554 $this->assign('onBehalfName', $this->_params['organization_name']);
555 $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
556 $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
557 }
558
559 //fix for CRM-3767
560 $assignCCInfo = FALSE;
561 if ($this->_amount > 0.0) {
562 $assignCCInfo = TRUE;
563 }
a7488080 564 elseif (!empty($this->_params['selectMembership'])) {
6a488035
TO
565 $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
566 if ($memFee > 0.0) {
567 $assignCCInfo = TRUE;
568 }
569 }
570
571 if ($this->_contributeMode == 'direct' && $assignCCInfo) {
f92fc7eb
CW
572 if ($this->_paymentProcessor &&
573 $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
574 ) {
6a488035
TO
575 $this->assign('account_holder', $this->_params['account_holder']);
576 $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
577 $this->assign('bank_name', $this->_params['bank_name']);
578 $this->assign('bank_account_number', $this->_params['bank_account_number']);
579 }
580 else {
581 $date = CRM_Utils_Date::format(CRM_Utils_array::value('credit_card_exp_date', $this->_params));
582 $date = CRM_Utils_Date::mysqlToIso($date);
583 $this->assign('credit_card_exp_date', $date);
584 $this->assign('credit_card_number',
353ffa53 585 CRM_Utils_System::mungeCreditCard(CRM_Utils_array::value('credit_card_number', $this->_params))
6a488035
TO
586 );
587 }
588 }
589
590 $this->assign('email',
591 $this->controller->exportValue('Main', "email-{$this->_bltID}")
592 );
593
594 // also assign the receipt_text
595 if (isset($this->_values['receipt_text'])) {
596 $this->assign('receipt_text', $this->_values['receipt_text']);
597 }
598 }
599
600 /**
fe482240 601 * Add the custom fields.
6a488035 602 *
100fef9d
CW
603 * @param int $id
604 * @param string $name
f4aaa82a
EM
605 * @param bool $viewOnly
606 * @param null $profileContactType
f92d1e2a 607 * @param array $fieldTypes
6a488035 608 */
00be9182 609 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
6a488035 610 if ($id) {
da8d9879 611 $contactID = $this->getContactID();
6a488035
TO
612
613 // we don't allow conflicting fields to be
614 // configured via profile - CRM 2100
615 $fieldsToIgnore = array(
616 'receive_date' => 1,
617 'trxn_id' => 1,
618 'invoice_id' => 1,
619 'net_amount' => 1,
620 'fee_amount' => 1,
621 'non_deductible_amount' => 1,
622 'total_amount' => 1,
623 'amount_level' => 1,
624 'contribution_status_id' => 1,
625 'payment_instrument' => 1,
626 'check_number' => 1,
627 'financial_type' => 1,
628 );
629
630 $fields = NULL;
631 if ($contactID && CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
632 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
633 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
634 );
635 }
636 else {
637 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
638 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
639 );
640 }
641
642 if ($fields) {
643 // unset any email-* fields since we already collect it, CRM-2888
644 foreach (array_keys($fields) as $fieldName) {
8af73472 645 if (substr($fieldName, 0, 6) == 'email-' && $profileContactType != 'honor') {
6a488035
TO
646 unset($fields[$fieldName]);
647 }
648 }
649
650 if (array_intersect_key($fields, $fieldsToIgnore)) {
651 $fields = array_diff_key($fields, $fieldsToIgnore);
652 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
653 }
654
655 $fields = array_diff_assoc($fields, $this->_fields);
656
657 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
658 $addCaptcha = FALSE;
659 foreach ($fields as $key => $field) {
660 if ($viewOnly &&
661 isset($field['data_type']) &&
662 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
663 ) {
664 // ignore file upload fields
665 continue;
666 }
667
133e2c99 668 if ($profileContactType) {
669 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
353ffa53
TO
670 $honoreeNamefields = array(
671 'prefix_id',
672 'first_name',
673 'last_name',
674 'suffix_id',
675 'organization_name',
389bcebf 676 'household_name',
353ffa53 677 );
133e2c99 678 if ($profileContactType == 'honor' && in_array($field['name'], $honoreeNamefields)) {
679 unset($fields[$field['name']]);
680 continue;
681 }
6a488035
TO
682 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
683 CRM_Core_BAO_UFGroup::buildProfile(
684 $this,
685 $field,
686 CRM_Profile_Form::MODE_CREATE,
687 $contactID,
133e2c99 688 TRUE,
689 $profileContactType
6a488035 690 );
133e2c99 691 $this->_fields[$profileContactType][$key] = $field;
6a488035
TO
692 }
693 else {
694 unset($fields[$key]);
695 }
696 }
697 else {
698 CRM_Core_BAO_UFGroup::buildProfile(
699 $this,
700 $field,
701 CRM_Profile_Form::MODE_CREATE,
702 $contactID,
703 TRUE
704 );
705 $this->_fields[$key] = $field;
706 }
71fc6ea4
DG
707 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
708 if ($field['add_captcha'] && !$this->_userID) {
6a488035
TO
709 $addCaptcha = TRUE;
710 }
711 }
712
713 $this->assign($name, $fields);
714
6a488035
TO
715 if ($addCaptcha && !$viewOnly) {
716 $captcha = CRM_Utils_ReCAPTCHA::singleton();
717 $captcha->add($this);
718 $this->assign('isCaptcha', TRUE);
719 }
720 }
721 }
722 }
723
f4aaa82a 724 /**
fe482240 725 * Check template file exists.
f92d1e2a
EM
726 *
727 * @param string $suffix
f4aaa82a
EM
728 *
729 * @return null|string
730 */
00be9182 731 public function checkTemplateFileExists($suffix = NULL) {
6a488035
TO
732 if ($this->_id) {
733 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
734 $template = CRM_Core_Form::getTemplate();
735 if ($template->template_exists($templateFile)) {
736 return $templateFile;
737 }
738 }
739 return NULL;
740 }
741
186c9c17 742 /**
fe482240 743 * Use the form name to create the tpl file name.
186c9c17
EM
744 *
745 * @return string
186c9c17 746 */
00be9182 747 public function getTemplateFileName() {
6a488035
TO
748 $fileName = $this->checkTemplateFileExists();
749 return $fileName ? $fileName : parent::getTemplateFileName();
750 }
751
186c9c17 752 /**
f92d1e2a
EM
753 * Add the extra.tpl in.
754 *
186c9c17 755 * Default extra tpl file basically just replaces .tpl with .extra.tpl
f92d1e2a 756 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
186c9c17
EM
757 *
758 * @return string
186c9c17 759 */
00be9182 760 public function overrideExtraTemplateFileName() {
6a488035
TO
761 $fileName = $this->checkTemplateFileExists('extra.');
762 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
763 }
764
765 /**
100fef9d 766 * Authenticate pledge user during online payment.
6a488035
TO
767 */
768 public function authenticatePledgeUser() {
769 //get the userChecksum and contact id
770 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
771 $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
772
773 //get pledge status and contact id
353ffa53
TO
774 $pledgeValues = array();
775 $pledgeParams = array('id' => $this->_values['pledge_id']);
6a488035
TO
776 $returnProperties = array('contact_id', 'status_id');
777 CRM_Core_DAO::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
778
779 //get all status
780 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
353ffa53
TO
781 $validStatus = array(
782 array_search('Pending', $allStatus),
6a488035
TO
783 array_search('In Progress', $allStatus),
784 array_search('Overdue', $allStatus),
785 );
786
787 $validUser = FALSE;
788 if ($this->_userID &&
789 $this->_userID == $pledgeValues['contact_id']
790 ) {
791 //check for authenticated user.
792 $validUser = TRUE;
793 }
794 elseif ($userChecksum && $pledgeValues['contact_id']) {
795 //check for anonymous user.
796 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($pledgeValues['contact_id'], $userChecksum);
797
798 //make sure cid is same as pledge contact id
799 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
800 $validUser = FALSE;
801 }
802 }
803
804 if (!$validUser) {
805 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."));
806 }
807
808 //check for valid pledge status.
809 if (!in_array($pledgeValues['status_id'], $validStatus)) {
810 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))));
811 }
812 }
813
814 /**
f92d1e2a
EM
815 * Cancel recurring contributions.
816 *
6a488035
TO
817 * In case user cancel recurring contribution,
818 * When we get the control back from payment gate way
819 * lets delete the recurring and related contribution.
389bcebf 820 */
6a488035
TO
821 public function cancelRecurring() {
822 $isCancel = CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject);
823 if ($isCancel) {
824 $isRecur = CRM_Utils_Request::retrieve('isRecur', 'Boolean', CRM_Core_DAO::$_nullObject);
825 $recurId = CRM_Utils_Request::retrieve('recurId', 'Positive', CRM_Core_DAO::$_nullObject);
826 //clean db for recurring contribution.
827 if ($isRecur && $recurId) {
828 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($recurId);
829 }
830 $contribId = CRM_Utils_Request::retrieve('contribId', 'Positive', CRM_Core_DAO::$_nullObject);
831 if ($contribId) {
832 CRM_Contribute_BAO_Contribution::deleteContribution($contribId);
833 }
834 }
835 }
96025800 836
42e3a033
EM
837 /**
838 * Build Membership Block in Contribution Pages.
839 *
42e3a033
EM
840 * @param int $cid
841 * Contact checked for having a current membership for a particular membership.
a46bfec1
EM
842 * @param bool $isContributionMainPage
843 * Is this the main page? If so add form input fields.
844 * (or better yet don't have this functionality in a function shared with forms that don't share it).
42e3a033
EM
845 * @param int $selectedMembershipTypeID
846 * Selected membership id.
847 * @param bool $thankPage
848 * Thank you page.
849 * @param null $isTest
850 *
851 * @return bool
852 * Is this a separate membership payment
853 */
854 protected function buildMembershipBlock(
855 $cid,
a46bfec1 856 $isContributionMainPage = FALSE,
42e3a033
EM
857 $selectedMembershipTypeID = NULL,
858 $thankPage = FALSE,
859 $isTest = NULL
860 ) {
861
862 $separateMembershipPayment = FALSE;
863 if ($this->_membershipBlock) {
864 $this->_currentMemberships = array();
865
42e3a033
EM
866 $membershipTypeIds = $membershipTypes = $radio = array();
867 $membershipPriceset = (!empty($this->_priceSetId) && $this->_useForMember) ? TRUE : FALSE;
868
869 $allowAutoRenewMembership = $autoRenewOption = FALSE;
870 $autoRenewMembershipTypeOptions = array();
871
a46bfec1 872 $separateMembershipPayment = CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock);
42e3a033
EM
873
874 if ($membershipPriceset) {
875 foreach ($this->_priceSet['fields'] as $pField) {
876 if (empty($pField['options'])) {
877 continue;
878 }
879 foreach ($pField['options'] as $opId => $opValues) {
880 if (empty($opValues['membership_type_id'])) {
881 continue;
882 }
883 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
884 }
885 }
886 }
a46bfec1
EM
887 elseif (!empty($this->_membershipBlock['membership_types'])) {
888 $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
42e3a033
EM
889 }
890
891 if (!empty($membershipTypeIds)) {
892 //set status message if wrong membershipType is included in membershipBlock
893 if (isset($this->_mid) && !$membershipPriceset) {
894 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
895 $this->_mid,
896 'membership_type_id'
897 );
898 if (!in_array($membershipTypeID, $membershipTypeIds)) {
899 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');
900 }
901 }
902
4c7b8a7d 903 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
42e3a033
EM
904 $this->_membershipTypeValues = $membershipTypeValues;
905 $endDate = NULL;
906 foreach ($membershipTypeIds as $value) {
907 $memType = $membershipTypeValues[$value];
908 if ($selectedMembershipTypeID != NULL) {
909 if ($memType['id'] == $selectedMembershipTypeID) {
910 $this->assign('minimum_fee',
911 CRM_Utils_Array::value('minimum_fee', $memType)
912 );
913 $this->assign('membership_name', $memType['name']);
914 if (!$thankPage && $cid) {
915 $membership = new CRM_Member_DAO_Membership();
916 $membership->contact_id = $cid;
917 $membership->membership_type_id = $memType['id'];
918 if ($membership->find(TRUE)) {
919 $this->assign('renewal_mode', TRUE);
920 $memType['current_membership'] = $membership->end_date;
921 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
922 }
923 }
924 $membershipTypes[] = $memType;
925 }
926 }
927 elseif ($memType['is_active']) {
928 $javascriptMethod = NULL;
08a4ce4e 929 $allowAutoRenewOpt = (int) $memType['auto_renew'];
42e3a033
EM
930 if (is_array($this->_paymentProcessors)) {
931 foreach ($this->_paymentProcessors as $id => $val) {
932 if (!$val['is_recur']) {
933 $allowAutoRenewOpt = 0;
934 continue;
935 }
936 }
937 }
938
939 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
940 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array::value($value, CRM_Utils_Array::value('auto_renew', $this->_membershipBlock));;
941
942 if ($allowAutoRenewOpt) {
943 $allowAutoRenewMembership = TRUE;
944 }
945
946 //add membership type.
947 $radio[$memType['id']] = $this->createElement('radio', NULL, NULL, NULL,
948 $memType['id'], $javascriptMethod
949 );
950 if ($cid) {
951 $membership = new CRM_Member_DAO_Membership();
952 $membership->contact_id = $cid;
953 $membership->membership_type_id = $memType['id'];
954
955 //show current membership, skip pending and cancelled membership records,
956 //because we take first membership record id for renewal
957 $membership->whereAdd('status_id != 5 AND status_id !=6');
958
959 if (!is_null($isTest)) {
960 $membership->is_test = $isTest;
961 }
962
963 //CRM-4297
964 $membership->orderBy('end_date DESC');
965
966 if ($membership->find(TRUE)) {
967 if (!$membership->end_date) {
968 unset($radio[$memType['id']]);
969 $this->assign('islifetime', TRUE);
970 continue;
971 }
972 $this->assign('renewal_mode', TRUE);
973 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
974 $memType['current_membership'] = $membership->end_date;
975 if (!$endDate) {
976 $endDate = $memType['current_membership'];
977 $this->_defaultMemTypeId = $memType['id'];
978 }
979 if ($memType['current_membership'] < $endDate) {
980 $endDate = $memType['current_membership'];
981 $this->_defaultMemTypeId = $memType['id'];
982 }
983 }
984 }
985 $membershipTypes[] = $memType;
986 }
987 }
988 }
989
a46bfec1
EM
990 $this->assign('membershipBlock', $this->_membershipBlock);
991 $this->assign('showRadio', $isContributionMainPage);
992 $this->assign('membershipTypes', $membershipTypes);
993 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
994 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
995 //give preference to user submitted auto_renew value.
996 $takeUserSubmittedAutoRenew = (!empty($_POST) || $this->isSubmitted()) ? TRUE : FALSE;
997 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
998
999 if ($isContributionMainPage) {
42e3a033 1000 if (!$membershipPriceset) {
a46bfec1 1001 if (!$this->_membershipBlock['is_required']) {
42e3a033
EM
1002 $this->assign('showRadioNoThanks', TRUE);
1003 $radio[''] = $this->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
1004 $this->addGroup($radio, 'selectMembership', NULL);
1005 }
a46bfec1 1006 elseif ($this->_membershipBlock['is_required'] && count($radio) == 1) {
42e3a033
EM
1007 $temp = array_keys($radio);
1008 $this->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
1009 $this->assign('singleMembership', TRUE);
1010 $this->assign('showRadio', FALSE);
1011 }
1012 else {
1013 $this->addGroup($radio, 'selectMembership', NULL);
1014 }
1015
1016 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
1017 }
1018 else {
1019 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId);
1020 $this->assign('autoRenewOption', $autoRenewOption);
1021 }
1022
1023 if (!$this->_values['is_pay_later'] && is_array($this->_paymentProcessors) && ($allowAutoRenewMembership || $autoRenewOption)) {
1024 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
1025 }
1026
1027 }
42e3a033
EM
1028 }
1029
1030 return $separateMembershipPayment;
1031 }
1032
90102a32
EM
1033 /**
1034 * Determine if recurring parameters need to be added to the form parameters.
1035 * - is_recur
1036 * - frequency_interval
1037 * - frequency_unit
1038 *
1039 * For membership this is based on the membership type.
1040 *
1041 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1042 *
1043 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1044 */
1045 protected function setRecurringMembershipParams() {
fd359255
EM
1046 if (!empty($this->_params['priceSetId']) && !empty($this->_params['selectMembership'])) {
1047 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1048 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1049 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1050 // this with an else (calculate for price set).
1051 $membershipTypes = CRM_Price_BAO_PriceSet::getMembershipTypesFromPriceSet($this->_params['priceSetId']);
1052 if (in_array($this->_params['selectMembership'], $membershipTypes['autorenew'])) {
1053 $this->_params['auto_renew'] = TRUE;
1054 }
1055 }
90102a32
EM
1056 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) &&
1057 CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])
1058 ) {
1059
1060 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
1061 // check if price set is not quick config
1062 if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
1063 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
1064 }
1065 else {
1066 // FIXME: set interval and unit based on selected membership type
1067 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1068 $this->_params['selectMembership'], 'duration_interval'
1069 );
1070 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1071 $this->_params['selectMembership'], 'duration_unit'
1072 );
1073 }
1074 }
1075 }
1076
6a488035 1077}