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