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