Merge branch 'VAT-417-Push' of github.com:Parag18/civicrm-core into Parag18-VAT-417...
[civicrm-core.git] / CRM / Contribute / Form / ContributionBase.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for processing a ontribution
38 *
39 */
40class CRM_Contribute_Form_ContributionBase extends CRM_Core_Form {
41
42 /**
43 * the id of the contribution page that we are proceessing
44 *
45 * @var int
46 * @public
47 */
48 public $_id;
49
50 /**
51 * the mode that we are in
52 *
53 * @var string
54 * @protect
55 */
56 public $_mode;
57
58 /**
59 * the contact id related to a membership
60 *
61 * @var int
62 * @public
63 */
64 public $_membershipContactID;
65
66 /**
67 * the values for the contribution db object
68 *
69 * @var array
70 * @protected
71 */
72 public $_values;
73
74 /**
75 * the paymentProcessor attributes for this page
76 *
77 * @var array
78 * @protected
79 */
80 public $_paymentProcessor;
81 public $_paymentObject = NULL;
82
83 /**
84 * The membership block for this page
85 *
86 * @var array
87 * @protected
88 */
89 public $_membershipBlock = NULL;
90
91 /**
92 * the default values for the form
93 *
94 * @var array
95 * @protected
96 */
97 protected $_defaults;
98
99 /**
100 * The params submitted by the form and computed by the app
101 *
102 * @var array
103 * @public
104 */
105 public $_params;
106
107 /**
108 * The fields involved in this contribution page
109 *
110 * @var array
111 * @public
112 */
113 public $_fields;
114
115 /**
116 * The billing location id for this contribiution page
117 *
118 * @var int
119 * @protected
120 */
121 public $_bltID;
122
123 /**
124 * Cache the amount to make things easier
125 *
126 * @var float
127 * @public
128 */
129 public $_amount;
130
131 /**
132 * pcp id
133 *
134 * @var integer
135 * @public
136 */
137 public $_pcpId;
138
139 /**
140 * pcp block
141 *
142 * @var array
143 * @public
144 */
145 public $_pcpBlock;
146
147 /**
148 * pcp info
149 *
150 * @var array
151 * @public
152 */
153 public $_pcpInfo;
154
5b757295 155 /**
156 * The contact id of the person for whom membership is being added or renewed based on the cid in the url,
157 * checksum, or session
0e5e0c2e 158 * @var int
5b757295 159 */
0e5e0c2e 160 public $_contactID;
5b757295 161
6a488035
TO
162 protected $_userID;
163
164 /**
165 * the Membership ID for membership renewal
166 *
167 * @var int
168 * @public
169 */
170 public $_membershipId;
171
172 /**
173 * Price Set ID, if the new price set method is used
174 *
175 * @var int
176 * @protected
177 */
178 public $_priceSetId;
179
180 /**
181 * Array of fields for the price set
182 *
183 * @var array
184 * @protected
185 */
186 public $_priceSet;
187
188 public $_action;
189
8af73472 190 /**
191 * Is honor block is enabled for this contribution?
192 *
193 * @var boolean
194 * @protected
195 */
196 public $_honor_block_is_active = FALSE;
197
dbddfb08
EM
198 /**
199 * Contribution mode e.g express for payment express, notify for off-site + notification back to CiviCRM
200 * @var string
201 */
202 public $_contributeMode;
203
204 /**
205 * contribution page supports memberships
206 * @var boolean
207 */
208 public $_useForMember;
6a488035
TO
209 /**
210 * Function to set variables up before form is built
211 *
212 * @return void
213 * @access public
214 */
215 public function preProcess() {
216 $config = CRM_Core_Config::singleton();
217 $session = CRM_Core_Session::singleton();
218
219 // current contribution page id
220 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
221 if (!$this->_id) {
d420cf02
DL
222 // seems like the session is corrupted and/or we lost the id trail
223 // lets just bump this to a regular session error and redirect user to main page
224 $this->controller->invalidKeyRedirect();
6a488035 225 }
d420cf02 226
5b757295 227 // this was used prior to the cleverer this_>getContactID - unsure now
6a488035 228 $this->_userID = $session->get('userID');
5b757295 229
8af73472 230 //Check if honor block is enabled for current contribution
bc0e993a 231 $ufJoinParams = array(
232 'module' => 'soft_credit',
233 'entity_table' => 'civicrm_contribution_page',
234 'entity_id' => $this->_id,
235 );
236 $ufJoin = new CRM_Core_DAO_UFJoin();
237 $ufJoin->copyValues($ufJoinParams);
238 $ufJoin->find(TRUE);
239 $this->_honor_block_is_active = $ufJoin->is_active;
8af73472 240
5b757295 241 $this->_contactID = $this->_membershipContactID = $this->getContactID();
6a488035 242 $this->_mid = NULL;
5b757295 243 if ($this->_contactID) {
6a488035
TO
244 $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
245 if ($this->_mid) {
246 $membership = new CRM_Member_DAO_Membership();
247 $membership->id = $this->_mid;
248
249 if ($membership->find(TRUE)) {
250 $this->_defaultMemTypeId = $membership->membership_type_id;
5b757295 251 if ($membership->contact_id != $this->_contactID) {
6fe8deba 252 $validMembership = FALSE;
6a488035 253 $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID);
6fe8deba
DS
254 if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) {
255 $this->_membershipContactID = $membership->contact_id;
256 $this->assign('membershipContactID', $this->_membershipContactID);
257 $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']);
258 $validMembership = TRUE;
259 } else {
51e89def
DS
260 $membershipType = new CRM_Member_BAO_MembershipType();
261 $membershipType->id = $membership->membership_type_id;
262 if ($membershipType->find(TRUE)) {
f9f0eff9
DG
263 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
264 // Convert to commma separated list.
265 $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
51e89def
DS
266 $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
267 if (array_key_exists($membership->contact_id, $permContacts)) {
268 $this->_membershipContactID = $membership->contact_id;
6fe8deba 269 $validMembership = TRUE;
51e89def
DS
270 }
271 }
6a488035 272 }
6fe8deba
DS
273 if (!$validMembership) {
274 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');
275 }
6a488035
TO
276 }
277 }
278 else {
279 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');
280 }
281 unset($membership);
282 }
283 }
284
285 // we do not want to display recently viewed items, so turn off
286 $this->assign('displayRecent', FALSE);
287 // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
288 // Use Browser Print instead.
289 $this->assign('browserPrint', TRUE);
290
291 // action
292 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
293 $this->assign('action', $this->_action);
294
295 // current mode
296 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
297
298 $this->_values = $this->get('values');
299 $this->_fields = $this->get('fields');
300 $this->_bltID = $this->get('bltID');
301 $this->_paymentProcessor = $this->get('paymentProcessor');
302 $this->_priceSetId = $this->get('priceSetId');
303 $this->_priceSet = $this->get('priceSet');
304
305 if (!$this->_values) {
306 // get all the values from the dao object
307 $this->_values = array();
308 $this->_fields = array();
309
310 CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
311
312 // check if form is active
a7488080 313 if (empty($this->_values['is_active'])) {
6a488035
TO
314 // form is inactive, die a fatal death
315 CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
316 }
317
318 // also check for billing informatin
319 // get the billing location type
180409a4 320 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
321 // CRM-8108 remove ts around Billing location type
322 //$this->_bltID = array_search( ts('Billing'), $locationTypes );
323 $this->_bltID = array_search('Billing', $locationTypes);
324 if (!$this->_bltID) {
325 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
326 }
327 $this->set('bltID', $this->_bltID);
328
329 // check for is_monetary status
330 $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values);
331 $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values);
332
333 //FIXME: to support multiple payment processors
334 if ($isMonetary &&
8cc574cf 335 (!$isPayLater || !empty($this->_values['payment_processor']))
6a488035
TO
336 ) {
337 $ppID = CRM_Utils_Array::value('payment_processor', $this->_values);
338 if (!$ppID) {
339 CRM_Core_Error::fatal(ts('A payment processor must be selected for this contribution page (contact the site administrator for assistance).'));
340 }
341
342 $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID);
343 $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds, $this->_mode);
344
345 $this->set('paymentProcessors', $this->_paymentProcessors);
346
347 //set default payment processor
348 if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) {
349 foreach ($this->_paymentProcessors as $ppId => $values) {
350 if ($values['is_default'] == 1 || (count($this->_paymentProcessors) == 1)) {
351 $defaultProcessorId = $ppId;
352 break;
353 }
354 }
355 }
356
357 if (isset($defaultProcessorId)) {
358 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode);
359 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
360 }
361
362 if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
363 foreach ($this->_paymentProcessors as $eachPaymentProcessor) {
364 // check selected payment processor is active
365 if (empty($eachPaymentProcessor)) {
366 CRM_Core_Error::fatal(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
367 }
368
369 // ensure that processor has a valid config
370 $this->_paymentObject = &CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this);
371 $error = $this->_paymentObject->checkConfig();
372 if (!empty($error)) {
373 CRM_Core_Error::fatal($error);
374 }
375 }
376 }
377 }
378
379 // get price info
380 // CRM-5095
9da8dc8c 381 CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page');
6a488035
TO
382
383 // this avoids getting E_NOTICE errors in php
384 $setNullFields = array(
385 'amount_block_is_active',
6a488035
TO
386 'is_allow_other_amount',
387 'footer_text',
388 );
389 foreach ($setNullFields as $f) {
390 if (!isset($this->_values[$f])) {
391 $this->_values[$f] = NULL;
392 }
393 }
394
395 //check if Membership Block is enabled, if Membership Fields are included in profile
396 //get membership section for this contribution page
397 $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
398 $this->set('membershipBlock', $this->_membershipBlock);
399
400 if ($this->_values['custom_pre_id']) {
401 $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
402 }
403
404 if ($this->_values['custom_post_id']) {
405 $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
406 }
407
408 if (((isset($postProfileType) && $postProfileType == 'Membership') ||
409 (isset($preProfileType) && $preProfileType == 'Membership')
410 ) &&
411 !$this->_membershipBlock['is_active']
412 ) {
413 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.'));
414 }
415
416 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
417
418 if ($pledgeBlock) {
419 $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock);
420 $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock);
421 $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock);
422 $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock);
423
424 //set pledge id in values
425 $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
426
427 //authenticate pledge user for pledge payment.
428 if ($pledgeId) {
429 $this->_values['pledge_id'] = $pledgeId;
430
431 //lets override w/ pledge campaign.
432 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
433 $pledgeId,
434 'campaign_id'
435 );
436 self::authenticatePledgeUser();
437 }
438 }
439 $this->set('values', $this->_values);
440 $this->set('fields', $this->_fields);
441 }
442
443 // Handle PCP
444 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
445 if ($pcpId) {
446 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
447 $this->_pcpId = $pcp['pcpId'];
448 $this->_pcpBlock = $pcp['pcpBlock'];
449 $this->_pcpInfo = $pcp['pcpInfo'];
450 }
451
452 // Link (button) for users to create their own Personal Campaign page
453 if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
454 $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign',
455 "action=add&reset=1&pageId={$this->_id}&component=contribute",
456 FALSE, NULL, TRUE
457 );
458 $this->assign('linkTextUrl', $linkTextUrl);
459 $this->assign('linkText', $linkText);
460 }
461
462 //set pledge block if block id is set
a7488080 463 if (!empty($this->_values['pledge_block_id'])) {
6a488035
TO
464 $this->assign('pledgeBlock', TRUE);
465 }
466
467 // check if one of the (amount , membership) bloks is active or not
468 $this->_membershipBlock = $this->get('membershipBlock');
469
470 if (!$this->_values['amount_block_is_active'] &&
471 !$this->_membershipBlock['is_active'] &&
472 !$this->_priceSetId
473 ) {
474 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.'));
475 }
476
477 if ($this->_values['amount_block_is_active']) {
478 $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
479 }
480
481 $this->_contributeMode = $this->get('contributeMode');
482 $this->assign('contributeMode', $this->_contributeMode);
483
484 //assigning is_monetary and is_email_receipt to template
485 $this->assign('is_monetary', $this->_values['is_monetary']);
486 $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
487 $this->assign('bltID', $this->_bltID);
488
489 //assign cancelSubscription URL to templates
490 $this->assign('cancelSubscriptionUrl',
491 CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)
492 );
493
494 // assigning title to template in case someone wants to use it, also setting CMS page title
495 if ($this->_pcpId) {
496 $this->assign('title', $this->_pcpInfo['title']);
497 CRM_Utils_System::setTitle($this->_pcpInfo['title']);
498 }
499 else {
500 $this->assign('title', $this->_values['title']);
501 CRM_Utils_System::setTitle($this->_values['title']);
502 }
503 $this->_defaults = array();
504
505 $this->_amount = $this->get('amount');
506
507 //CRM-6907
508 $config = CRM_Core_Config::singleton();
509 $config->defaultCurrency = CRM_Utils_Array::value('currency',
510 $this->_values,
511 $config->defaultCurrency
512 );
513
514 //lets allow user to override campaign.
515 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
516 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
517 $this->_values['campaign_id'] = $campID;
518 }
519
520 //do check for cancel recurring and clean db, CRM-7696
521 if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) {
522 self::cancelRecurring();
523 }
524 }
525
526 /**
527 * set the default values
528 *
529 * @return void
530 * @access public
531 */
532 function setDefaultValues() {
533 return $this->_defaults;
534 }
535
536 /**
537 * assign the minimal set of variables to the template
538 *
539 * @return void
540 * @access public
541 */
542 function assignToTemplate() {
543 $name = CRM_Utils_Array::value('billing_first_name', $this->_params);
a7488080 544 if (!empty($this->_params['billing_middle_name'])) {
6a488035
TO
545 $name .= " {$this->_params['billing_middle_name']}";
546 }
547 $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
548 $name = trim($name);
549 $this->assign('billingName', $name);
550 $this->set('name', $name);
551
552 $this->assign('paymentProcessor', $this->_paymentProcessor);
553 $vars = array(
554 'amount', 'currencyID',
555 'credit_card_type', 'trxn_id', 'amount_level',
556 );
557
558 $config = CRM_Core_Config::singleton();
8cc574cf 559 if (isset($this->_values['is_recur']) && !empty($this->_paymentProcessor['is_recur'])) {
6a488035
TO
560 $this->assign('is_recur_enabled', 1);
561 $vars = array_merge($vars, array(
562 'is_recur', 'frequency_interval', 'frequency_unit',
563 'installments',
564 ));
565 }
566
567 if (in_array('CiviPledge', $config->enableComponents) &&
568 CRM_Utils_Array::value('is_pledge', $this->_params) == 1
569 ) {
570 $this->assign('pledge_enabled', 1);
571
572 $vars = array_merge($vars, array(
573 'is_pledge',
574 'pledge_frequency_interval',
575 'pledge_frequency_unit',
576 'pledge_installments',
577 ));
578 }
579
580 if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
581 $this->_params['amount_level'] = '';
582 }
583
584 foreach ($vars as $v) {
3fb990f4 585 if (isset($this->_params[$v])) {
6a488035
TO
586 if ($v == 'frequency_unit' || $v == 'pledge_frequency_unit') {
587 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
588 if (array_key_exists($this->_params[$v], $frequencyUnits)) {
589 $this->_params[$v] = $frequencyUnits[$this->_params[$v]];
590 }
591 }
735fe42d
PJ
592 if ($v == "amount" && $this->_params[$v] === 0) {
593 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
3fb990f4 594 }
6a488035
TO
595 $this->assign($v, $this->_params[$v]);
596 }
597 }
598
599 // assign the address formatted up for display
600 $addressParts = array(
601 "street_address-{$this->_bltID}",
602 "city-{$this->_bltID}",
603 "postal_code-{$this->_bltID}",
604 "state_province-{$this->_bltID}",
605 "country-{$this->_bltID}",
606 );
607
608 $addressFields = array();
609 foreach ($addressParts as $part) {
610 list($n, $id) = explode('-', $part);
611 $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $this->_params);
612 }
613
614 $this->assign('address', CRM_Utils_Address::format($addressFields));
615
a7488080 616 if (!empty($this->_params['hidden_onbehalf_profile'])) {
6a488035
TO
617 $this->assign('onBehalfName', $this->_params['organization_name']);
618 $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
619 $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
620 }
621
622 //fix for CRM-3767
623 $assignCCInfo = FALSE;
624 if ($this->_amount > 0.0) {
625 $assignCCInfo = TRUE;
626 }
a7488080 627 elseif (!empty($this->_params['selectMembership'])) {
6a488035
TO
628 $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
629 if ($memFee > 0.0) {
630 $assignCCInfo = TRUE;
631 }
632 }
633
634 if ($this->_contributeMode == 'direct' && $assignCCInfo) {
f92fc7eb
CW
635 if ($this->_paymentProcessor &&
636 $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
637 ) {
6a488035
TO
638 $this->assign('payment_type', $this->_paymentProcessor['payment_type']);
639 $this->assign('account_holder', $this->_params['account_holder']);
640 $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
641 $this->assign('bank_name', $this->_params['bank_name']);
642 $this->assign('bank_account_number', $this->_params['bank_account_number']);
643 }
644 else {
645 $date = CRM_Utils_Date::format(CRM_Utils_array::value('credit_card_exp_date', $this->_params));
646 $date = CRM_Utils_Date::mysqlToIso($date);
647 $this->assign('credit_card_exp_date', $date);
648 $this->assign('credit_card_number',
649 CRM_Utils_System::mungeCreditCard(CRM_Utils_array::value('credit_card_number', $this->_params))
650 );
651 }
652 }
653
654 $this->assign('email',
655 $this->controller->exportValue('Main', "email-{$this->_bltID}")
656 );
657
658 // also assign the receipt_text
659 if (isset($this->_values['receipt_text'])) {
660 $this->assign('receipt_text', $this->_values['receipt_text']);
661 }
662 }
663
664 /**
665 * Function to add the custom fields
666 *
f4aaa82a
EM
667 * @param $id
668 * @param $name
669 * @param bool $viewOnly
670 * @param null $profileContactType
671 * @param null $fieldTypes
672 *
355ba699 673 * @return void
6a488035
TO
674 * @access public
675 */
133e2c99 676 function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
6a488035
TO
677 $stateCountryMap = array();
678
679 if ($id) {
da8d9879 680 $contactID = $this->getContactID();
6a488035
TO
681
682 // we don't allow conflicting fields to be
683 // configured via profile - CRM 2100
684 $fieldsToIgnore = array(
685 'receive_date' => 1,
686 'trxn_id' => 1,
687 'invoice_id' => 1,
688 'net_amount' => 1,
689 'fee_amount' => 1,
690 'non_deductible_amount' => 1,
691 'total_amount' => 1,
692 'amount_level' => 1,
693 'contribution_status_id' => 1,
694 'payment_instrument' => 1,
695 'check_number' => 1,
696 'financial_type' => 1,
697 );
698
699 $fields = NULL;
700 if ($contactID && CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
701 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
702 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
703 );
704 }
705 else {
706 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
707 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
708 );
709 }
710
711 if ($fields) {
712 // unset any email-* fields since we already collect it, CRM-2888
713 foreach (array_keys($fields) as $fieldName) {
8af73472 714 if (substr($fieldName, 0, 6) == 'email-' && $profileContactType != 'honor') {
6a488035
TO
715 unset($fields[$fieldName]);
716 }
717 }
718
719 if (array_intersect_key($fields, $fieldsToIgnore)) {
720 $fields = array_diff_key($fields, $fieldsToIgnore);
721 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
722 }
723
724 $fields = array_diff_assoc($fields, $this->_fields);
725
726 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
727 $addCaptcha = FALSE;
728 foreach ($fields as $key => $field) {
729 if ($viewOnly &&
730 isset($field['data_type']) &&
731 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
732 ) {
733 // ignore file upload fields
734 continue;
735 }
736
737 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
738 if ($prefixName == 'state_province' || $prefixName == 'country' || $prefixName == 'county') {
739 if (!array_key_exists($index, $stateCountryMap)) {
740 $stateCountryMap[$index] = array();
741 }
742 $stateCountryMap[$index][$prefixName] = $key;
f5b34faf 743
744 if ($prefixName == "state_province") {
133e2c99 745 if ($profileContactType == 'onbehalf') {
f5b34faf 746 //CRM-11881: Bypass required-ness check for state/province on Contribution Confirm page
747 //as already done during Contribution registration via onBehalf's quickForm
748 $field['is_required'] = FALSE;
749 }
750 else {
751 if (count($this->_submitValues)) {
fe2c5efd 752 $locationTypeId = $field['location_type_id'];
753 if (array_key_exists("country-{$locationTypeId}", $fields) &&
754 array_key_exists("state_province-{$locationTypeId}", $fields) &&
755 !empty($this->_submitValues["country-{$locationTypeId}"])) {
f5b34faf 756 $field['is_required'] =
fe2c5efd 757 CRM_Core_Payment_Form::checkRequiredStateProvince($this, "country-{$locationTypeId}");
f5b34faf 758 }
759 }
760 }
761 }
6a488035
TO
762 }
763
133e2c99 764 if ($profileContactType) {
765 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
766 $honoreeNamefields = array('prefix_id', 'first_name', 'last_name', 'suffix_id', 'organization_name', 'household_name');
767 if ($profileContactType == 'honor' && in_array($field['name'], $honoreeNamefields)) {
768 unset($fields[$field['name']]);
769 continue;
770 }
6a488035
TO
771 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
772 CRM_Core_BAO_UFGroup::buildProfile(
773 $this,
774 $field,
775 CRM_Profile_Form::MODE_CREATE,
776 $contactID,
133e2c99 777 TRUE,
778 $profileContactType
6a488035 779 );
133e2c99 780 $this->_fields[$profileContactType][$key] = $field;
6a488035
TO
781 }
782 else {
783 unset($fields[$key]);
784 }
785 }
786 else {
787 CRM_Core_BAO_UFGroup::buildProfile(
788 $this,
789 $field,
790 CRM_Profile_Form::MODE_CREATE,
791 $contactID,
792 TRUE
793 );
794 $this->_fields[$key] = $field;
795 }
71fc6ea4
DG
796 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
797 if ($field['add_captcha'] && !$this->_userID) {
6a488035
TO
798 $addCaptcha = TRUE;
799 }
800 }
801
802 $this->assign($name, $fields);
803
804 CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap);
805
806 if ($addCaptcha && !$viewOnly) {
807 $captcha = CRM_Utils_ReCAPTCHA::singleton();
808 $captcha->add($this);
809 $this->assign('isCaptcha', TRUE);
810 }
811 }
812 }
813 }
814
f4aaa82a
EM
815 /**
816 * Check template file exists
817 * @param null $suffix
818 *
819 * @return null|string
820 */
6a488035
TO
821 function checkTemplateFileExists($suffix = NULL) {
822 if ($this->_id) {
823 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
824 $template = CRM_Core_Form::getTemplate();
825 if ($template->template_exists($templateFile)) {
826 return $templateFile;
827 }
828 }
829 return NULL;
830 }
831
186c9c17
EM
832 /**
833 * Use the form name to create the tpl file name
834 *
835 * @return string
836 * @access public
837 */
838 /**
839 * @return string
840 */
6a488035
TO
841 function getTemplateFileName() {
842 $fileName = $this->checkTemplateFileExists();
843 return $fileName ? $fileName : parent::getTemplateFileName();
844 }
845
186c9c17
EM
846 /**
847 * Default extra tpl file basically just replaces .tpl with .extra.tpl
848 * i.e. we dont override
849 *
850 * @return string
851 * @access public
852 */
853 /**
854 * @return string
855 */
6a488035
TO
856 function overrideExtraTemplateFileName() {
857 $fileName = $this->checkTemplateFileExists('extra.');
858 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
859 }
860
861 /**
862 * Function to authenticate pledge user during online payment.
863 *
864 * @access public
865 *
355ba699 866 * @return void
6a488035
TO
867 */
868 public function authenticatePledgeUser() {
869 //get the userChecksum and contact id
870 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
871 $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
872
873 //get pledge status and contact id
874 $pledgeValues = array();
875 $pledgeParams = array('id' => $this->_values['pledge_id']);
876 $returnProperties = array('contact_id', 'status_id');
877 CRM_Core_DAO::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
878
879 //get all status
880 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
881 $validStatus = array(array_search('Pending', $allStatus),
882 array_search('In Progress', $allStatus),
883 array_search('Overdue', $allStatus),
884 );
885
886 $validUser = FALSE;
887 if ($this->_userID &&
888 $this->_userID == $pledgeValues['contact_id']
889 ) {
890 //check for authenticated user.
891 $validUser = TRUE;
892 }
893 elseif ($userChecksum && $pledgeValues['contact_id']) {
894 //check for anonymous user.
895 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($pledgeValues['contact_id'], $userChecksum);
896
897 //make sure cid is same as pledge contact id
898 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
899 $validUser = FALSE;
900 }
901 }
902
903 if (!$validUser) {
904 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."));
905 }
906
907 //check for valid pledge status.
908 if (!in_array($pledgeValues['status_id'], $validStatus)) {
909 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))));
910 }
911 }
912
913 /**
914 * In case user cancel recurring contribution,
915 * When we get the control back from payment gate way
916 * lets delete the recurring and related contribution.
917 *
918 **/
919 public function cancelRecurring() {
920 $isCancel = CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject);
921 if ($isCancel) {
922 $isRecur = CRM_Utils_Request::retrieve('isRecur', 'Boolean', CRM_Core_DAO::$_nullObject);
923 $recurId = CRM_Utils_Request::retrieve('recurId', 'Positive', CRM_Core_DAO::$_nullObject);
924 //clean db for recurring contribution.
925 if ($isRecur && $recurId) {
926 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($recurId);
927 }
928 $contribId = CRM_Utils_Request::retrieve('contribId', 'Positive', CRM_Core_DAO::$_nullObject);
929 if ($contribId) {
930 CRM_Contribute_BAO_Contribution::deleteContribution($contribId);
931 }
932 }
933 }
934}
935