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