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