Merge pull request #22318 from jitendrapurohit/state_name
[civicrm-core.git] / CRM / Contribute / BAO / ContributionPage.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 use Civi\Api4\Contribution;
19 use Civi\Api4\LineItem;
20
21 /**
22 * This class contains Contribution Page related functions.
23 */
24 class CRM_Contribute_BAO_ContributionPage extends CRM_Contribute_DAO_ContributionPage {
25
26 /**
27 * Creates a contribution page.
28 *
29 * @param array $params
30 *
31 * @return CRM_Contribute_DAO_ContributionPage
32 */
33 public static function create($params) {
34 $financialTypeId = NULL;
35 if (!empty($params['id']) && !CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id'], NULL, 1)) {
36 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $params['id'], 'financial_type_id');
37 }
38
39 if (isset($params['payment_processor']) && is_array($params['payment_processor'])) {
40 $params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
41 }
42 $hook = empty($params['id']) ? 'create' : 'edit';
43 CRM_Utils_Hook::pre($hook, 'ContributionPage', CRM_Utils_Array::value('id', $params), $params);
44 $dao = new CRM_Contribute_DAO_ContributionPage();
45 $dao->copyValues($params);
46 $dao->save();
47 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
48 CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_contribution_page', $params['financial_type_id']);
49 }
50 CRM_Utils_Hook::post($hook, 'ContributionPage', $dao->id, $dao);
51 CRM_Core_PseudoConstant::flush();
52 return $dao;
53 }
54
55 /**
56 * Update the is_active flag in the db.
57 *
58 * @deprecated - this bypasses hooks.
59 *
60 * @param int $id
61 * Id of the database record.
62 * @param bool $is_active
63 * Value we want to set the is_active field.
64 *
65 * @return bool
66 * true if we found and updated the object, else false
67 */
68 public static function setIsActive($id, $is_active) {
69 return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'is_active', $is_active);
70 }
71
72 /**
73 * Load values for a contribution page.
74 *
75 * @param int $id
76 * @param array $values
77 */
78 public static function setValues($id, &$values) {
79 $modules = ['CiviContribute', 'soft_credit', 'on_behalf'];
80 $values['custom_pre_id'] = $values['custom_post_id'] = NULL;
81
82 $params = ['id' => $id];
83 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $values);
84
85 // get the profile ids
86 $ufJoinParams = [
87 'entity_table' => 'civicrm_contribution_page',
88 'entity_id' => $id,
89 ];
90
91 // retrieve profile id as also unserialize module_data corresponding to each $module
92 foreach ($modules as $module) {
93 $ufJoinParams['module'] = $module;
94 $ufJoin = new CRM_Core_DAO_UFJoin();
95 $ufJoin->copyValues($ufJoinParams);
96 if ($module == 'CiviContribute') {
97 $ufJoin->orderBy('weight asc');
98 $ufJoin->find();
99 while ($ufJoin->fetch()) {
100 if ($ufJoin->weight == 1) {
101 $values['custom_pre_id'] = $ufJoin->uf_group_id;
102 }
103 else {
104 $values['custom_post_id'] = $ufJoin->uf_group_id;
105 }
106 }
107 }
108 else {
109 $ufJoin->find(TRUE);
110 if (!$ufJoin->is_active) {
111 continue;
112 }
113 $params = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoin->module_data, TRUE, $module);
114 $values = array_merge($params, $values);
115 if ($module == 'soft_credit') {
116 $values['honoree_profile_id'] = $ufJoin->uf_group_id;
117 $values['honor_block_is_active'] = $ufJoin->is_active;
118 }
119 else {
120 $values['onbehalf_profile_id'] = $ufJoin->uf_group_id;
121 }
122 }
123 }
124 }
125
126 /**
127 * Send the emails.
128 *
129 * @param int $contactID
130 * Contact id.
131 * @param array $values
132 * Associated array of fields.
133 * @param bool $isTest
134 * If in test mode.
135 * @param bool $returnMessageText
136 * Return the message text instead of sending the mail.
137 *
138 * @param array $fieldTypes
139 *
140 * @throws \CRM_Core_Exception
141 */
142 public static function sendMail($contactID, $values, $isTest = FALSE, $returnMessageText = FALSE, $fieldTypes = NULL) {
143 $gIds = [];
144 $params = ['custom_pre_id' => [], 'custom_post_id' => []];
145 $email = NULL;
146
147 // We are trying to fight the good fight against leaky variables (CRM-17519) so let's get really explicit
148 // about ensuring the variables we want for the template are defined.
149 // @todo add to this until all tpl params are explicit in this function and not waltzing around the codebase.
150 // Next stage is to remove this & ensure there are no e-notices - ie. all are set before they hit this fn.
151 $valuesRequiredForTemplate = [
152 'customPre',
153 'customPost',
154 'customPre_grouptitle',
155 'customPost_grouptitle',
156 'useForMember',
157 'membership_assign',
158 'amount',
159 'receipt_date',
160 'is_pay_later',
161 ];
162
163 foreach ($valuesRequiredForTemplate as $valueRequiredForTemplate) {
164 if (!isset($values[$valueRequiredForTemplate])) {
165 $values[$valueRequiredForTemplate] = NULL;
166 }
167 }
168
169 if (isset($values['custom_pre_id'])) {
170 $preProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_pre_id']);
171 if ($preProfileType == 'Membership' && !empty($values['membership_id'])) {
172 $params['custom_pre_id'] = [
173 [
174 'member_id',
175 '=',
176 $values['membership_id'],
177 0,
178 0,
179 ],
180 ];
181 }
182 elseif ($preProfileType == 'Contribution' && !empty($values['contribution_id'])) {
183 $params['custom_pre_id'] = [
184 [
185 'contribution_id',
186 '=',
187 $values['contribution_id'],
188 0,
189 0,
190 ],
191 ];
192 }
193
194 $gIds['custom_pre_id'] = $values['custom_pre_id'];
195 }
196
197 if (isset($values['custom_post_id'])) {
198 $postProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_post_id']);
199 if ($postProfileType == 'Membership' && !empty($values['membership_id'])) {
200 $params['custom_post_id'] = [
201 [
202 'member_id',
203 '=',
204 $values['membership_id'],
205 0,
206 0,
207 ],
208 ];
209 }
210 elseif ($postProfileType == 'Contribution' && !empty($values['contribution_id'])) {
211 $params['custom_post_id'] = [
212 [
213 'contribution_id',
214 '=',
215 $values['contribution_id'],
216 0,
217 0,
218 ],
219 ];
220 }
221
222 $gIds['custom_post_id'] = $values['custom_post_id'];
223 }
224
225 if (!empty($values['is_for_organization'])) {
226 if (!empty($values['membership_id'])) {
227 $params['onbehalf_profile'] = [
228 [
229 'member_id',
230 '=',
231 $values['membership_id'],
232 0,
233 0,
234 ],
235 ];
236 }
237 elseif (!empty($values['contribution_id'])) {
238 $params['onbehalf_profile'] = [
239 [
240 'contribution_id',
241 '=',
242 $values['contribution_id'],
243 0,
244 0,
245 ],
246 ];
247 }
248 }
249
250 //check whether it is a test drive
251 if ($isTest && !empty($params['custom_pre_id'])) {
252 $params['custom_pre_id'][] = [
253 'contribution_test',
254 '=',
255 1,
256 0,
257 0,
258 ];
259 }
260
261 if ($isTest && !empty($params['custom_post_id'])) {
262 $params['custom_post_id'][] = [
263 'contribution_test',
264 '=',
265 1,
266 0,
267 0,
268 ];
269 }
270
271 if (!$returnMessageText && !empty($gIds)) {
272 //send notification email if field values are set (CRM-1941)
273 foreach ($gIds as $key => $gId) {
274 if ($gId) {
275 $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
276 if ($email) {
277 $val = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $contactID, CRM_Utils_Array::value($key, $params), TRUE);
278 CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
279 }
280 }
281 }
282 }
283
284 if (!empty($values['is_email_receipt']) || !empty($values['onbehalf_dupe_alert']) ||
285 $returnMessageText
286 ) {
287 $template = CRM_Core_Smarty::singleton();
288
289 if (!array_key_exists('related_contact', $values)) {
290 [$displayName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE, CRM_Core_BAO_LocationType::getBilling());
291 }
292 // get primary location email if no email exist( for billing location).
293 if (!$email) {
294 [$displayName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
295 }
296 if (empty($displayName)) {
297 [$displayName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
298 }
299
300 //for display profile need to get individual contact id,
301 //hence get it from related_contact if on behalf of org true CRM-3767
302 //CRM-5001 Contribution/Membership:: On Behalf of Organization,
303 //If profile GROUP contain the Individual type then consider the
304 //profile is of Individual ( including the custom data of membership/contribution )
305 //IF Individual type not present in profile then it is consider as Organization data.
306 $userID = $contactID;
307 if ($preID = CRM_Utils_Array::value('custom_pre_id', $values)) {
308 if (!empty($values['related_contact'])) {
309 $preProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($preID);
310 if (in_array('Individual', $preProfileTypes) || in_array('Contact', $preProfileTypes)) {
311 //Take Individual contact ID
312 $userID = $values['related_contact'] ?? NULL;
313 }
314 }
315 [$values['customPre_grouptitle'], $values['customPre']] = self::getProfileNameAndFields($preID, $userID, $params['custom_pre_id']);
316 }
317 $userID = $contactID;
318 if ($postID = CRM_Utils_Array::value('custom_post_id', $values)) {
319 if (!empty($values['related_contact'])) {
320 $postProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($postID);
321 if (in_array('Individual', $postProfileTypes) || in_array('Contact', $postProfileTypes)) {
322 //Take Individual contact ID
323 $userID = $values['related_contact'] ?? NULL;
324 }
325 }
326 list($values['customPost_grouptitle'], $values['customPost']) = self::getProfileNameAndFields($postID, $userID, $params['custom_post_id']);
327 }
328 if (isset($values['honor'])) {
329 $honorValues = $values['honor'];
330 $template->_values = ['honoree_profile_id' => $values['honoree_profile_id']];
331 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields(
332 $template,
333 $honorValues['honor_profile_values'],
334 $honorValues['honor_id']
335 );
336 }
337
338 $title = $values['title'] ?? CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($values['contribution_page_id']);
339
340 // Set email variables explicitly to avoid leaky smarty variables.
341 // All of these will be assigned to the template, replacing any that might be assigned elsewhere.
342 $tplParams = [
343 'email' => $email,
344 'receiptFromEmail' => $values['receipt_from_email'] ?? NULL,
345 'contactID' => $contactID,
346 'displayName' => $displayName,
347 'contributionID' => $values['contribution_id'] ?? NULL,
348 'contributionOtherID' => $values['contribution_other_id'] ?? NULL,
349 // CRM-5095
350 'lineItem' => $values['lineItem'] ?? NULL,
351 // CRM-5095
352 'priceSetID' => $values['priceSetID'] ?? NULL,
353 'title' => $title,
354 'isShare' => $values['is_share'] ?? NULL,
355 'thankyou_title' => $values['thankyou_title'] ?? NULL,
356 'customPre' => $values['customPre'],
357 'customPre_grouptitle' => $values['customPre_grouptitle'],
358 'customPost' => $values['customPost'],
359 'customPost_grouptitle' => $values['customPost_grouptitle'],
360 'useForMember' => $values['useForMember'],
361 'membership_assign' => $values['membership_assign'],
362 'amount' => $values['amount'],
363 'is_pay_later' => $values['is_pay_later'],
364 'receipt_date' => !$values['receipt_date'] ? NULL : date('YmdHis', strtotime($values['receipt_date'])),
365 'pay_later_receipt' => $values['pay_later_receipt'] ?? NULL,
366 'honor_block_is_active' => $values['honor_block_is_active'] ?? NULL,
367 'contributionStatus' => $values['contribution_status'] ?? NULL,
368 'currency' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $values['contribution_id'], 'currency') ?? CRM_Core_Config::singleton()->defaultCurrency,
369 ];
370
371 if (!empty($values['financial_type_id'])) {
372 $tplParams['financialTypeId'] = $values['financial_type_id'];
373 $tplParams['financialTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
374 $values['financial_type_id']);
375 // Legacy support
376 $tplParams['contributionTypeName'] = $tplParams['financialTypeName'];
377 }
378
379 if ($contributionPageId = CRM_Utils_Array::value('id', $values)) {
380 $tplParams['contributionPageId'] = $contributionPageId;
381 }
382
383 // address required during receipt processing (pdf and email receipt)
384 if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
385 $tplParams['address'] = $displayAddress;
386 }
387
388 // CRM-6976
389 $originalCCReceipt = $values['cc_receipt'] ?? NULL;
390
391 // cc to related contacts of contributor OR the one who
392 // signs up. Is used for cases like - on behalf of
393 // contribution / signup ..etc
394 if (array_key_exists('related_contact', $values)) {
395 list($ccDisplayName, $ccEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($values['related_contact']);
396 $ccMailId = "{$ccDisplayName} <{$ccEmail}>";
397
398 //@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used
399 $values['cc_receipt'] = !empty($values['cc_receipt']) ? ($values['cc_receipt'] . ',' . $ccMailId) : $ccMailId;
400
401 // reset primary-email in the template
402 $tplParams['email'] = $ccEmail;
403
404 $tplParams['onBehalfName'] = $displayName;
405 $tplParams['onBehalfEmail'] = $email;
406
407 if (!empty($values['onbehalf_profile_id'])) {
408 self::buildCustomDisplay($values['onbehalf_profile_id'], 'onBehalfProfile', $contactID, $template, $params['onbehalf_profile'], $fieldTypes);
409 }
410 }
411
412 // use either the contribution or membership receipt, based on whether it’s a membership-related contrib or not
413 $sendTemplateParams = [
414 'groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
415 'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt',
416 'contactId' => $contactID,
417 'tplParams' => $tplParams,
418 'isTest' => $isTest,
419 'PDFFilename' => 'receipt.pdf',
420 ];
421
422 if ($returnMessageText) {
423 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
424 return [
425 'subject' => $subject,
426 'body' => $message,
427 'to' => $displayName,
428 'html' => $html,
429 ];
430 }
431
432 if (empty($values['receipt_from_name']) && empty($values['receipt_from_name'])) {
433 list($values['receipt_from_name'], $values['receipt_from_email']) = CRM_Core_BAO_Domain::getNameAndEmail();
434 }
435
436 if ($values['is_email_receipt']) {
437 $sendTemplateParams['from'] = CRM_Utils_Array::value('receipt_from_name', $values) . ' <' . $values['receipt_from_email'] . '>';
438 $sendTemplateParams['toName'] = $displayName;
439 $sendTemplateParams['toEmail'] = $email;
440 $sendTemplateParams['cc'] = $values['cc_receipt'] ?? NULL;
441 $sendTemplateParams['bcc'] = $values['bcc_receipt'] ?? NULL;
442 //send email with pdf invoice
443 if (Civi::settings()->get('invoice_is_email_pdf')) {
444 $sendTemplateParams['isEmailPdf'] = TRUE;
445 $sendTemplateParams['contributionId'] = $values['contribution_id'];
446 }
447 list($sent, $subject, $message) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
448 }
449
450 // send duplicate alert, if dupe match found during on-behalf-of processing.
451 if (!empty($values['onbehalf_dupe_alert'])) {
452 $sendTemplateParams['groupName'] = 'msg_tpl_workflow_contribution';
453 $sendTemplateParams['valueName'] = 'contribution_dupalert';
454 $sendTemplateParams['from'] = ts('Automatically Generated') . " <{$values['receipt_from_email']}>";
455 $sendTemplateParams['toName'] = $values['receipt_from_name'] ?? NULL;
456 $sendTemplateParams['toEmail'] = $values['receipt_from_email'] ?? NULL;
457 $sendTemplateParams['tplParams']['onBehalfID'] = $contactID;
458 $sendTemplateParams['tplParams']['receiptMessage'] = $message;
459
460 // fix cc and reset back to original, CRM-6976
461 $sendTemplateParams['cc'] = $originalCCReceipt;
462
463 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
464 }
465 }
466 }
467
468 /**
469 * Get the profile title and fields.
470 *
471 * @param int $gid
472 * @param int $cid
473 * @param array $params
474 * @param array $fieldTypes
475 *
476 * @return array
477 *
478 * @throws \CRM_Core_Exception
479 */
480 protected static function getProfileNameAndFields($gid, $cid, $params, $fieldTypes = []) {
481 $groupTitle = NULL;
482 $values = [];
483 if ($gid) {
484 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
485 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
486 foreach ($fields as $k => $v) {
487 if (!$groupTitle) {
488 $groupTitle = $v['groupDisplayTitle'];
489 }
490 // suppress all file fields from display and formatting fields
491 if (
492 $v['data_type'] === 'File' || $v['name'] === 'image_URL' || $v['field_type'] === 'Formatting') {
493 unset($fields[$k]);
494 }
495
496 if (!empty($fieldTypes) && (!in_array($v['field_type'], $fieldTypes))) {
497 unset($fields[$k]);
498 }
499 }
500
501 CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
502 }
503 }
504 return [$groupTitle, $values];
505 }
506
507 /**
508 * Send the emails for Recurring Contribution Notification.
509 *
510 * @param int $contributionID
511 * @param string $type
512 * TxnType.
513 * Contribution page id.
514 * @param object $recur
515 *
516 * @throws \API_Exception
517 */
518 public static function recurringNotify($contributionID, $type, $recur): void {
519 $contribution = Contribution::get(FALSE)
520 ->addWhere('id', '=', $contributionID)
521 ->setSelect([
522 'contribution_page_id',
523 'contact_id',
524 'contribution_recur_id',
525 'contribution_recur_id.is_email_receipt',
526 'contribution_page_id.title',
527 'contribution_page_id.is_email_receipt',
528 'contribution_page_id.receipt_from_name',
529 'contribution_page_id.receipt_from_email',
530 'contribution_page_id.cc_receipt',
531 'contribution_page_id.bcc_receipt',
532 ])
533 ->execute()->first();
534
535 $isMembership = !empty(LineItem::get(FALSE)
536 ->addWhere('contribution_id', '=', $contributionID)
537 ->addWhere('entity_table', '=', 'civicrm_membership')
538 ->addSelect('id')->execute()->first());
539
540 if ($contribution['contribution_recur_id.is_email_receipt'] || $contribution['contribution_page_id.is_email_receipt']) {
541 if ($contribution['contribution_page_id.receipt_from_email']) {
542 $receiptFromName = $contribution['contribution_page_id.receipt_from_name'];
543 $receiptFromEmail = $contribution['contribution_page_id.receipt_from_email'];
544 }
545 else {
546 [$receiptFromName, $receiptFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail();
547 }
548
549 $receiptFrom = "$receiptFromName <$receiptFromEmail>";
550 [$displayName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution['contact_id'], FALSE);
551 $templatesParams = [
552 'groupName' => 'msg_tpl_workflow_contribution',
553 'valueName' => 'contribution_recurring_notify',
554 'contactId' => $contribution['contact_id'],
555 'tplParams' => [
556 'recur_frequency_interval' => $recur->frequency_interval,
557 'recur_frequency_unit' => $recur->frequency_unit,
558 'recur_installments' => $recur->installments,
559 'recur_start_date' => $recur->start_date,
560 'recur_end_date' => $recur->end_date,
561 'recur_amount' => $recur->amount,
562 'recur_txnType' => $type,
563 'displayName' => $displayName,
564 'receipt_from_name' => $receiptFromName,
565 'receipt_from_email' => $receiptFromEmail,
566 'auto_renew_membership' => $isMembership,
567 ],
568 'from' => $receiptFrom,
569 'toName' => $displayName,
570 'toEmail' => $email,
571 ];
572 //CRM-13811
573 $templatesParams['cc'] = $contribution['contribution_page_id.cc_receipt'];
574 $templatesParams['bcc'] = $contribution['contribution_page_id.cc_receipt'];
575 if ($recur->id) {
576 // in some cases its just recurringNotify() thats called for the first time and these urls don't get set.
577 // like in PaypalPro, & therefore we set it here additionally.
578 $template = CRM_Core_Smarty::singleton();
579 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
580 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'cancel');
581 $template->assign('cancelSubscriptionUrl', $url);
582
583 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing');
584 $template->assign('updateSubscriptionBillingUrl', $url);
585
586 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update');
587 $template->assign('updateSubscriptionUrl', $url);
588 }
589
590 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
591
592 if ($sent) {
593 CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
594 }
595 else {
596 CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
597 }
598 }
599 }
600
601 /**
602 * Add the custom fields for contribution page (ie profile).
603 *
604 * @deprecated assigning values to smarty like this is risky because
605 * - it is hard to debug since $name is used in the assign
606 * - it is potentially 'leaky' - it's better to do this on the form
607 * or close to where it is used / required. See CRM-17519 for leakage e.g.
608 *
609 * @param int $gid
610 * Uf group id.
611 * @param string $name
612 * @param int $cid
613 * Contact id.
614 * @param $template
615 * @param array $params
616 * Params to build component whereclause.
617 *
618 * @param array|null $fieldTypes
619 */
620 public static function buildCustomDisplay($gid, $name, $cid, &$template, &$params, $fieldTypes = NULL) {
621 list($groupTitle, $values) = self::getProfileNameAndFields($gid, $cid, $params, $fieldTypes);
622 if (!empty($values)) {
623 $template->assign($name, $values);
624 }
625 $template->assign($name . "_grouptitle", $groupTitle);
626 }
627
628 /**
629 * Make a copy of a contribution page, including all the blocks in the page.
630 *
631 * @param int $id
632 * The contribution page id to copy.
633 *
634 * @return CRM_Contribute_DAO_ContributionPage
635 */
636 public static function copy($id) {
637 $session = CRM_Core_Session::singleton();
638
639 $fieldsFix = [
640 'prefix' => [
641 'title' => ts('Copy of') . ' ',
642 ],
643 'replace' => [
644 'created_id' => $session->get('userID'),
645 'created_date' => date('YmdHis'),
646 ],
647 ];
648 $copy = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', [
649 'id' => $id,
650 ], NULL, $fieldsFix);
651
652 //copying all the blocks pertaining to the contribution page
653 $copyPledgeBlock = CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', [
654 'entity_id' => $id,
655 'entity_table' => 'civicrm_contribution_page',
656 ], [
657 'entity_id' => $copy->id,
658 ]);
659
660 $copyMembershipBlock = CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', [
661 'entity_id' => $id,
662 'entity_table' => 'civicrm_contribution_page',
663 ], [
664 'entity_id' => $copy->id,
665 ]);
666
667 $copyUFJoin = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', [
668 'entity_id' => $id,
669 'entity_table' => 'civicrm_contribution_page',
670 ], [
671 'entity_id' => $copy->id,
672 ]);
673
674 $copyWidget = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', [
675 'contribution_page_id' => $id,
676 ], [
677 'contribution_page_id' => $copy->id,
678 ]);
679
680 //copy price sets
681 CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_contribution_page', $id, $copy->id);
682
683 $copyTellFriend = CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', [
684 'entity_id' => $id,
685 'entity_table' => 'civicrm_contribution_page',
686 ], [
687 'entity_id' => $copy->id,
688 ]);
689
690 $copyPersonalCampaignPages = CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', [
691 'entity_id' => $id,
692 'entity_table' => 'civicrm_contribution_page',
693 ], [
694 'entity_id' => $copy->id,
695 'target_entity_id' => $copy->id,
696 ]);
697
698 $copyPremium = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', [
699 'entity_id' => $id,
700 'entity_table' => 'civicrm_contribution_page',
701 ], [
702 'entity_id' => $copy->id,
703 ]);
704 $premiumQuery = "
705 SELECT id
706 FROM civicrm_premiums
707 WHERE entity_table = 'civicrm_contribution_page'
708 AND entity_id ={$id}";
709
710 $premiumDao = CRM_Core_DAO::executeQuery($premiumQuery);
711 while ($premiumDao->fetch()) {
712 if ($premiumDao->id) {
713 CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', [
714 'premiums_id' => $premiumDao->id,
715 ], [
716 'premiums_id' => $copyPremium->id,
717 ]);
718 }
719 }
720
721 $copy->save();
722
723 CRM_Utils_Hook::copy('ContributionPage', $copy);
724
725 return $copy;
726 }
727
728 /**
729 * Get info for all sections enable/disable.
730 *
731 * @param array $contribPageIds
732 * @return array
733 * info regarding all sections.
734 */
735 public static function getSectionInfo($contribPageIds = []) {
736 $info = [];
737 $whereClause = NULL;
738 if (is_array($contribPageIds) && !empty($contribPageIds)) {
739 $whereClause = 'WHERE civicrm_contribution_page.id IN ( ' . implode(', ', $contribPageIds) . ' )';
740 }
741
742 $sections = [
743 'settings',
744 'amount',
745 'membership',
746 'custom',
747 'thankyou',
748 'friend',
749 'pcp',
750 'widget',
751 'premium',
752 ];
753 $query = "
754 SELECT civicrm_contribution_page.id as id,
755 civicrm_contribution_page.financial_type_id as settings,
756 amount_block_is_active as amount,
757 civicrm_membership_block.id as membership,
758 civicrm_uf_join.id as custom,
759 civicrm_contribution_page.thankyou_title as thankyou,
760 civicrm_tell_friend.id as friend,
761 civicrm_pcp_block.id as pcp,
762 civicrm_contribution_widget.id as widget,
763 civicrm_premiums.id as premium
764 FROM civicrm_contribution_page
765 LEFT JOIN civicrm_membership_block ON ( civicrm_membership_block.entity_id = civicrm_contribution_page.id
766 AND civicrm_membership_block.entity_table = 'civicrm_contribution_page'
767 AND civicrm_membership_block.is_active = 1 )
768 LEFT JOIN civicrm_uf_join ON ( civicrm_uf_join.entity_id = civicrm_contribution_page.id
769 AND civicrm_uf_join.entity_table = 'civicrm_contribution_page'
770 AND module = 'CiviContribute'
771 AND civicrm_uf_join.is_active = 1 )
772 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_contribution_page.id
773 AND civicrm_tell_friend.entity_table = 'civicrm_contribution_page'
774 AND civicrm_tell_friend.is_active = 1)
775 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_contribution_page.id
776 AND civicrm_pcp_block.entity_table = 'civicrm_contribution_page'
777 AND civicrm_pcp_block.is_active = 1 )
778 LEFT JOIN civicrm_contribution_widget ON ( civicrm_contribution_widget.contribution_page_id = civicrm_contribution_page.id
779 AND civicrm_contribution_widget.is_active = 1 )
780 LEFT JOIN civicrm_premiums ON ( civicrm_premiums.entity_id = civicrm_contribution_page.id
781 AND civicrm_premiums.entity_table = 'civicrm_contribution_page'
782 AND civicrm_premiums.premiums_active = 1 )
783 $whereClause";
784
785 $contributionPage = CRM_Core_DAO::executeQuery($query);
786 while ($contributionPage->fetch()) {
787 if (!isset($info[$contributionPage->id]) || !is_array($info[$contributionPage->id])) {
788 $info[$contributionPage->id] = array_fill_keys(array_values($sections), FALSE);
789 }
790 foreach ($sections as $section) {
791 if ($contributionPage->$section) {
792 $info[$contributionPage->id][$section] = TRUE;
793 }
794 }
795 }
796
797 return $info;
798 }
799
800 /**
801 * Get options for a given field.
802 * @see CRM_Core_DAO::buildOptions
803 *
804 * @param string $fieldName
805 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
806 * @param array $props : whatever is known about this dao object
807 *
808 * @return array|bool
809 */
810 public static function buildOptions($fieldName, $context = NULL, $props = []) {
811 $params = [];
812 // Special logic for fields whose options depend on context or properties
813 switch ($fieldName) {
814 case 'financial_type_id':
815 // https://lab.civicrm.org/dev/core/issues/547 if CiviContribute not enabled this causes an invalid query
816 // @todo - the component is enabled check should be done within getIncomeFinancialType
817 // It looks to me like test cover was NOT added to cover the change
818 // that added this so we need to assume there is no test cover
819 if (array_key_exists('CiviContribute', CRM_Core_Component::getEnabledComponents())) {
820 // if check_permission has been passed in (not Null) then restrict.
821 return CRM_Financial_BAO_FinancialType::getIncomeFinancialType($props['check_permissions'] ?? TRUE);
822 }
823 return [];
824 }
825 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
826 }
827
828 /**
829 * Get or Set honor/on_behalf params for processing module_data or setting default values.
830 *
831 * @param array $params :
832 * @param bool $setDefault : If yes then returns array to used for setting default value afterward
833 * @param string $module : processing module_data for which module? e.g. soft_credit, on_behalf
834 *
835 * @return array|string
836 */
837 public static function formatModuleData($params, $setDefault, $module) {
838 $tsLocale = CRM_Core_I18n::getLocale();
839 $config = CRM_Core_Config::singleton();
840 $json = $jsonDecode = NULL;
841 $multilingual = CRM_Core_I18n::isMultilingual();
842
843 $moduleDataFormat = [
844 'soft_credit' => [
845 1 => 'soft_credit_types',
846 'multilingual' => [
847 'honor_block_title',
848 'honor_block_text',
849 ],
850 ],
851 'on_behalf' => [
852 1 => 'is_for_organization',
853 'multilingual' => [
854 'for_organization',
855 ],
856 ],
857 ];
858
859 //When we are fetching the honor params respecting both multi and mono lingual state
860 //and setting it to default param of Contribution Page's Main and Setting form
861 if ($setDefault) {
862 $jsonDecode = json_decode($params);
863 $jsonDecode = (array) $jsonDecode->$module;
864 if ($multilingual && !empty($jsonDecode[$tsLocale])) {
865 //multilingual state
866 foreach ($jsonDecode[$tsLocale] as $column => $value) {
867 $jsonDecode[$column] = $value;
868 }
869 unset($jsonDecode[$tsLocale]);
870 }
871 elseif (!empty($jsonDecode['default'])) {
872 //monolingual state, or an undefined value in multilingual
873 $jsonDecode += (array) $jsonDecode['default'];
874 unset($jsonDecode['default']);
875 }
876 return $jsonDecode;
877 }
878
879 //check and handle multilingual honoree params
880 if (!$multilingual) {
881 //if in singlelingual state simply return the array format
882 $json = [$module => NULL];
883 foreach ($moduleDataFormat[$module] as $key => $attribute) {
884 if ($key === 'multilingual') {
885 $json[$module]['default'] = [];
886 foreach ($attribute as $attr) {
887 $json[$module]['default'][$attr] = $params[$attr];
888 }
889 }
890 else {
891 $json[$module][$attribute] = $params[$attribute];
892 }
893 }
894 $json = json_encode($json);
895 }
896 else {
897 //if in multilingual state then retrieve the module_data against this contribution and
898 //merge with earlier module_data json data to current so not to lose earlier multilingual module_data information
899 $json = [$module => NULL];
900 foreach ($moduleDataFormat[$module] as $key => $attribute) {
901 if ($key === 'multilingual') {
902 $json[$module][$tsLocale] = [];
903 foreach ($attribute as $attr) {
904 $json[$module][$tsLocale][$attr] = $params[$attr];
905 }
906 }
907 else {
908 $json[$module][$attribute] = $params[$attribute];
909 }
910 }
911
912 $ufJoinDAO = new CRM_Core_DAO_UFJoin();
913 $ufJoinDAO->module = $module;
914 $ufJoinDAO->entity_id = $params['id'];
915 $ufJoinDAO->find(TRUE);
916 $jsonData = json_decode($ufJoinDAO->module_data);
917 if ($jsonData) {
918 $json[$module] = array_merge((array) $jsonData->$module, $json[$module]);
919 }
920 $json = json_encode($json);
921 }
922 return $json;
923 }
924
925 /**
926 * Generate html for pdf in confirmation receipt email attachment.
927 * @param int $contributionId
928 * Contribution Page Id.
929 * @param int $userID
930 * Contact id for contributor.
931 * @return array
932 */
933 public static function addInvoicePdfToEmail($contributionId, $userID) {
934 $contributionID = [$contributionId];
935 $contactId = [$userID];
936 $pdfParams = [
937 'output' => 'pdf_invoice',
938 'forPage' => 'confirmpage',
939 ];
940 $pdfHtml = CRM_Contribute_Form_Task_Invoice::printPDF($contributionID, $pdfParams, $contactId);
941 return $pdfHtml;
942 }
943
944 /**
945 * Helper to determine if the page supports separate membership payments.
946 *
947 * @param int $id form id
948 *
949 * @return bool
950 * isSeparateMembershipPayment
951 */
952 public static function getIsMembershipPayment($id) {
953 $membershipBlocks = civicrm_api3('membership_block', 'get', [
954 'entity_table' => 'civicrm_contribution_page',
955 'entity_id' => $id,
956 'sequential' => TRUE,
957 ]);
958 if (!$membershipBlocks['count']) {
959 return FALSE;
960 }
961 return $membershipBlocks['values'][0]['is_separate_payment'];
962 }
963
964 }