Merge pull request #20208 from seamuslee001/move_acl_test_trait
[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 ];
369
370 if (!empty($values['financial_type_id'])) {
371 $tplParams['financialTypeId'] = $values['financial_type_id'];
372 $tplParams['financialTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
373 $values['financial_type_id']);
374 // Legacy support
375 $tplParams['contributionTypeName'] = $tplParams['financialTypeName'];
376 }
377
378 if ($contributionPageId = CRM_Utils_Array::value('id', $values)) {
379 $tplParams['contributionPageId'] = $contributionPageId;
380 }
381
382 // address required during receipt processing (pdf and email receipt)
383 if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
384 $tplParams['address'] = $displayAddress;
385 }
386
387 // CRM-6976
388 $originalCCReceipt = $values['cc_receipt'] ?? NULL;
389
390 // cc to related contacts of contributor OR the one who
391 // signs up. Is used for cases like - on behalf of
392 // contribution / signup ..etc
393 if (array_key_exists('related_contact', $values)) {
394 list($ccDisplayName, $ccEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($values['related_contact']);
395 $ccMailId = "{$ccDisplayName} <{$ccEmail}>";
396
397 //@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used
398 $values['cc_receipt'] = !empty($values['cc_receipt']) ? ($values['cc_receipt'] . ',' . $ccMailId) : $ccMailId;
399
400 // reset primary-email in the template
401 $tplParams['email'] = $ccEmail;
402
403 $tplParams['onBehalfName'] = $displayName;
404 $tplParams['onBehalfEmail'] = $email;
405
406 if (!empty($values['onbehalf_profile_id'])) {
407 self::buildCustomDisplay($values['onbehalf_profile_id'], 'onBehalfProfile', $contactID, $template, $params['onbehalf_profile'], $fieldTypes);
408 }
409 }
410
411 // use either the contribution or membership receipt, based on whether it’s a membership-related contrib or not
412 $sendTemplateParams = [
413 'groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
414 'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt',
415 'contactId' => $contactID,
416 'tplParams' => $tplParams,
417 'isTest' => $isTest,
418 'PDFFilename' => 'receipt.pdf',
419 ];
420
421 if ($returnMessageText) {
422 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
423 return [
424 'subject' => $subject,
425 'body' => $message,
426 'to' => $displayName,
427 'html' => $html,
428 ];
429 }
430
431 if (empty($values['receipt_from_name']) && empty($values['receipt_from_name'])) {
432 list($values['receipt_from_name'], $values['receipt_from_email']) = CRM_Core_BAO_Domain::getNameAndEmail();
433 }
434
435 if ($values['is_email_receipt']) {
436 $sendTemplateParams['from'] = CRM_Utils_Array::value('receipt_from_name', $values) . ' <' . $values['receipt_from_email'] . '>';
437 $sendTemplateParams['toName'] = $displayName;
438 $sendTemplateParams['toEmail'] = $email;
439 $sendTemplateParams['cc'] = $values['cc_receipt'] ?? NULL;
440 $sendTemplateParams['bcc'] = $values['bcc_receipt'] ?? NULL;
441 //send email with pdf invoice
442 if (Civi::settings()->get('invoicing') && Civi::settings()->get('invoice_is_email_pdf')) {
443 $sendTemplateParams['isEmailPdf'] = TRUE;
444 $sendTemplateParams['contributionId'] = $values['contribution_id'];
445 }
446 list($sent, $subject, $message) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
447 }
448
449 // send duplicate alert, if dupe match found during on-behalf-of processing.
450 if (!empty($values['onbehalf_dupe_alert'])) {
451 $sendTemplateParams['groupName'] = 'msg_tpl_workflow_contribution';
452 $sendTemplateParams['valueName'] = 'contribution_dupalert';
453 $sendTemplateParams['from'] = ts('Automatically Generated') . " <{$values['receipt_from_email']}>";
454 $sendTemplateParams['toName'] = $values['receipt_from_name'] ?? NULL;
455 $sendTemplateParams['toEmail'] = $values['receipt_from_email'] ?? NULL;
456 $sendTemplateParams['tplParams']['onBehalfID'] = $contactID;
457 $sendTemplateParams['tplParams']['receiptMessage'] = $message;
458
459 // fix cc and reset back to original, CRM-6976
460 $sendTemplateParams['cc'] = $originalCCReceipt;
461
462 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
463 }
464 }
465 }
466
467 /**
468 * Get the profile title and fields.
469 *
470 * @param int $gid
471 * @param int $cid
472 * @param array $params
473 * @param array $fieldTypes
474 *
475 * @return array
476 *
477 * @throws \CRM_Core_Exception
478 */
479 protected static function getProfileNameAndFields($gid, $cid, $params, $fieldTypes = []) {
480 $groupTitle = NULL;
481 $values = [];
482 if ($gid) {
483 if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
484 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
485 foreach ($fields as $k => $v) {
486 if (!$groupTitle) {
487 $groupTitle = $v['groupDisplayTitle'];
488 }
489 // suppress all file fields from display and formatting fields
490 if (
491 $v['data_type'] === 'File' || $v['name'] === 'image_URL' || $v['field_type'] === 'Formatting') {
492 unset($fields[$k]);
493 }
494
495 if (!empty($fieldTypes) && (!in_array($v['field_type'], $fieldTypes))) {
496 unset($fields[$k]);
497 }
498 }
499
500 CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
501 }
502 }
503 return [$groupTitle, $values];
504 }
505
506 /**
507 * Send the emails for Recurring Contribution Notification.
508 *
509 * @param int $contributionID
510 * @param string $type
511 * TxnType.
512 * Contribution page id.
513 * @param object $recur
514 *
515 * @throws \API_Exception
516 */
517 public static function recurringNotify($contributionID, $type, $recur): void {
518 $contribution = Contribution::get(FALSE)
519 ->addWhere('id', '=', $contributionID)
520 ->setSelect([
521 'contribution_page_id',
522 'contact_id',
523 'contribution_recur_id',
524 'contribution_recur.is_email_receipt',
525 'contribution_page.title',
526 'contribution_page.is_email_receipt',
527 'contribution_page.receipt_from_name',
528 'contribution_page.receipt_from_email',
529 'contribution_page.cc_receipt',
530 'contribution_page.bcc_receipt',
531 ])
532 ->execute()->first();
533
534 $isMembership = !empty(LineItem::get(FALSE)
535 ->addWhere('contribution_id', '=', $contributionID)
536 ->addWhere('entity_table', '=', 'civicrm_membership')
537 ->addSelect('id')->execute()->first());
538
539 if ($contribution['contribution_recur.is_email_receipt'] || $contribution['contribution_page.is_email_receipt']) {
540 if ($contribution['contribution_page.receipt_from_email']) {
541 $receiptFromName = $contribution['contribution_page.receipt_from_name'];
542 $receiptFromEmail = $contribution['contribution_page.receipt_from_email'];
543 }
544 else {
545 [$receiptFromName, $receiptFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail();
546 }
547
548 $receiptFrom = "$receiptFromName <$receiptFromEmail>";
549 [$displayName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution['contact_id'], FALSE);
550 $templatesParams = [
551 'groupName' => 'msg_tpl_workflow_contribution',
552 'valueName' => 'contribution_recurring_notify',
553 'contactId' => $contribution['contact_id'],
554 'tplParams' => [
555 'recur_frequency_interval' => $recur->frequency_interval,
556 'recur_frequency_unit' => $recur->frequency_unit,
557 'recur_installments' => $recur->installments,
558 'recur_start_date' => $recur->start_date,
559 'recur_end_date' => $recur->end_date,
560 'recur_amount' => $recur->amount,
561 'recur_txnType' => $type,
562 'displayName' => $displayName,
563 'receipt_from_name' => $receiptFromName,
564 'receipt_from_email' => $receiptFromEmail,
565 'auto_renew_membership' => $isMembership,
566 ],
567 'from' => $receiptFrom,
568 'toName' => $displayName,
569 'toEmail' => $email,
570 ];
571 //CRM-13811
572 $templatesParams['cc'] = $contribution['contribution_page.cc_receipt'];
573 $templatesParams['bcc'] = $contribution['contribution_page.cc_receipt'];
574 if ($recur->id) {
575 // in some cases its just recurringNotify() thats called for the first time and these urls don't get set.
576 // like in PaypalPro, & therefore we set it here additionally.
577 $template = CRM_Core_Smarty::singleton();
578 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
579 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'cancel');
580 $template->assign('cancelSubscriptionUrl', $url);
581
582 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing');
583 $template->assign('updateSubscriptionBillingUrl', $url);
584
585 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update');
586 $template->assign('updateSubscriptionUrl', $url);
587 }
588
589 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
590
591 if ($sent) {
592 CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
593 }
594 else {
595 CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
596 }
597 }
598 }
599
600 /**
601 * Add the custom fields for contribution page (ie profile).
602 *
603 * @deprecated assigning values to smarty like this is risky because
604 * - it is hard to debug since $name is used in the assign
605 * - it is potentially 'leaky' - it's better to do this on the form
606 * or close to where it is used / required. See CRM-17519 for leakage e.g.
607 *
608 * @param int $gid
609 * Uf group id.
610 * @param string $name
611 * @param int $cid
612 * Contact id.
613 * @param $template
614 * @param array $params
615 * Params to build component whereclause.
616 *
617 * @param array|null $fieldTypes
618 */
619 public static function buildCustomDisplay($gid, $name, $cid, &$template, &$params, $fieldTypes = NULL) {
620 list($groupTitle, $values) = self::getProfileNameAndFields($gid, $cid, $params, $fieldTypes);
621 if (!empty($values)) {
622 $template->assign($name, $values);
623 }
624 $template->assign($name . "_grouptitle", $groupTitle);
625 }
626
627 /**
628 * Make a copy of a contribution page, including all the blocks in the page.
629 *
630 * @param int $id
631 * The contribution page id to copy.
632 *
633 * @return CRM_Contribute_DAO_ContributionPage
634 */
635 public static function copy($id) {
636 $session = CRM_Core_Session::singleton();
637
638 $fieldsFix = [
639 'prefix' => [
640 'title' => ts('Copy of') . ' ',
641 ],
642 'replace' => [
643 'created_id' => $session->get('userID'),
644 'created_date' => date('YmdHis'),
645 ],
646 ];
647 $copy = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', [
648 'id' => $id,
649 ], NULL, $fieldsFix);
650
651 //copying all the blocks pertaining to the contribution page
652 $copyPledgeBlock = CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', [
653 'entity_id' => $id,
654 'entity_table' => 'civicrm_contribution_page',
655 ], [
656 'entity_id' => $copy->id,
657 ]);
658
659 $copyMembershipBlock = CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', [
660 'entity_id' => $id,
661 'entity_table' => 'civicrm_contribution_page',
662 ], [
663 'entity_id' => $copy->id,
664 ]);
665
666 $copyUFJoin = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', [
667 'entity_id' => $id,
668 'entity_table' => 'civicrm_contribution_page',
669 ], [
670 'entity_id' => $copy->id,
671 ]);
672
673 $copyWidget = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', [
674 'contribution_page_id' => $id,
675 ], [
676 'contribution_page_id' => $copy->id,
677 ]);
678
679 //copy price sets
680 CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_contribution_page', $id, $copy->id);
681
682 $copyTellFriend = CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', [
683 'entity_id' => $id,
684 'entity_table' => 'civicrm_contribution_page',
685 ], [
686 'entity_id' => $copy->id,
687 ]);
688
689 $copyPersonalCampaignPages = CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', [
690 'entity_id' => $id,
691 'entity_table' => 'civicrm_contribution_page',
692 ], [
693 'entity_id' => $copy->id,
694 'target_entity_id' => $copy->id,
695 ]);
696
697 $copyPremium = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', [
698 'entity_id' => $id,
699 'entity_table' => 'civicrm_contribution_page',
700 ], [
701 'entity_id' => $copy->id,
702 ]);
703 $premiumQuery = "
704 SELECT id
705 FROM civicrm_premiums
706 WHERE entity_table = 'civicrm_contribution_page'
707 AND entity_id ={$id}";
708
709 $premiumDao = CRM_Core_DAO::executeQuery($premiumQuery);
710 while ($premiumDao->fetch()) {
711 if ($premiumDao->id) {
712 CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', [
713 'premiums_id' => $premiumDao->id,
714 ], [
715 'premiums_id' => $copyPremium->id,
716 ]);
717 }
718 }
719
720 $copy->save();
721
722 CRM_Utils_Hook::copy('ContributionPage', $copy);
723
724 return $copy;
725 }
726
727 /**
728 * Get info for all sections enable/disable.
729 *
730 * @param array $contribPageIds
731 * @return array
732 * info regarding all sections.
733 */
734 public static function getSectionInfo($contribPageIds = []) {
735 $info = [];
736 $whereClause = NULL;
737 if (is_array($contribPageIds) && !empty($contribPageIds)) {
738 $whereClause = 'WHERE civicrm_contribution_page.id IN ( ' . implode(', ', $contribPageIds) . ' )';
739 }
740
741 $sections = [
742 'settings',
743 'amount',
744 'membership',
745 'custom',
746 'thankyou',
747 'friend',
748 'pcp',
749 'widget',
750 'premium',
751 ];
752 $query = "
753 SELECT civicrm_contribution_page.id as id,
754 civicrm_contribution_page.financial_type_id as settings,
755 amount_block_is_active as amount,
756 civicrm_membership_block.id as membership,
757 civicrm_uf_join.id as custom,
758 civicrm_contribution_page.thankyou_title as thankyou,
759 civicrm_tell_friend.id as friend,
760 civicrm_pcp_block.id as pcp,
761 civicrm_contribution_widget.id as widget,
762 civicrm_premiums.id as premium
763 FROM civicrm_contribution_page
764 LEFT JOIN civicrm_membership_block ON ( civicrm_membership_block.entity_id = civicrm_contribution_page.id
765 AND civicrm_membership_block.entity_table = 'civicrm_contribution_page'
766 AND civicrm_membership_block.is_active = 1 )
767 LEFT JOIN civicrm_uf_join ON ( civicrm_uf_join.entity_id = civicrm_contribution_page.id
768 AND civicrm_uf_join.entity_table = 'civicrm_contribution_page'
769 AND module = 'CiviContribute'
770 AND civicrm_uf_join.is_active = 1 )
771 LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_contribution_page.id
772 AND civicrm_tell_friend.entity_table = 'civicrm_contribution_page'
773 AND civicrm_tell_friend.is_active = 1)
774 LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_contribution_page.id
775 AND civicrm_pcp_block.entity_table = 'civicrm_contribution_page'
776 AND civicrm_pcp_block.is_active = 1 )
777 LEFT JOIN civicrm_contribution_widget ON ( civicrm_contribution_widget.contribution_page_id = civicrm_contribution_page.id
778 AND civicrm_contribution_widget.is_active = 1 )
779 LEFT JOIN civicrm_premiums ON ( civicrm_premiums.entity_id = civicrm_contribution_page.id
780 AND civicrm_premiums.entity_table = 'civicrm_contribution_page'
781 AND civicrm_premiums.premiums_active = 1 )
782 $whereClause";
783
784 $contributionPage = CRM_Core_DAO::executeQuery($query);
785 while ($contributionPage->fetch()) {
786 if (!isset($info[$contributionPage->id]) || !is_array($info[$contributionPage->id])) {
787 $info[$contributionPage->id] = array_fill_keys(array_values($sections), FALSE);
788 }
789 foreach ($sections as $section) {
790 if ($contributionPage->$section) {
791 $info[$contributionPage->id][$section] = TRUE;
792 }
793 }
794 }
795
796 return $info;
797 }
798
799 /**
800 * Get options for a given field.
801 * @see CRM_Core_DAO::buildOptions
802 *
803 * @param string $fieldName
804 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
805 * @param array $props : whatever is known about this dao object
806 *
807 * @return array|bool
808 */
809 public static function buildOptions($fieldName, $context = NULL, $props = []) {
810 $params = [];
811 // Special logic for fields whose options depend on context or properties
812 switch ($fieldName) {
813 case 'financial_type_id':
814 // @fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
815 // @fixme - https://lab.civicrm.org/dev/core/issues/547 if CiviContribute not enabled this causes an invalid query
816 // because $relationTypeId is not set in CRM_Financial_BAO_FinancialType::getIncomeFinancialType()
817 if (array_key_exists('CiviContribute', CRM_Core_Component::getEnabledComponents())) {
818 return CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
819 }
820 return [];
821 }
822 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
823 }
824
825 /**
826 * Get or Set honor/on_behalf params for processing module_data or setting default values.
827 *
828 * @param array $params :
829 * @param bool $setDefault : If yes then returns array to used for setting default value afterward
830 * @param string $module : processing module_data for which module? e.g. soft_credit, on_behalf
831 *
832 * @return array|string
833 */
834 public static function formatModuleData($params, $setDefault = FALSE, $module) {
835 $tsLocale = CRM_Core_I18n::getLocale();
836 $config = CRM_Core_Config::singleton();
837 $json = $jsonDecode = NULL;
838 $multilingual = CRM_Core_I18n::isMultilingual();
839
840 $moduleDataFormat = [
841 'soft_credit' => [
842 1 => 'soft_credit_types',
843 'multilingual' => [
844 'honor_block_title',
845 'honor_block_text',
846 ],
847 ],
848 'on_behalf' => [
849 1 => 'is_for_organization',
850 'multilingual' => [
851 'for_organization',
852 ],
853 ],
854 ];
855
856 //When we are fetching the honor params respecting both multi and mono lingual state
857 //and setting it to default param of Contribution Page's Main and Setting form
858 if ($setDefault) {
859 $jsonDecode = json_decode($params);
860 $jsonDecode = (array) $jsonDecode->$module;
861 if (!$multilingual && !empty($jsonDecode['default'])) {
862 //monolingual state
863 $jsonDecode += (array) $jsonDecode['default'];
864 unset($jsonDecode['default']);
865 }
866 elseif (!empty($jsonDecode[$tsLocale])) {
867 //multilingual state
868 foreach ($jsonDecode[$tsLocale] as $column => $value) {
869 $jsonDecode[$column] = $value;
870 }
871 unset($jsonDecode[$tsLocale]);
872 }
873 return $jsonDecode;
874 }
875
876 //check and handle multilingual honoree params
877 if (!$multilingual) {
878 //if in singlelingual state simply return the array format
879 $json = [$module => NULL];
880 foreach ($moduleDataFormat[$module] as $key => $attribute) {
881 if ($key === 'multilingual') {
882 $json[$module]['default'] = [];
883 foreach ($attribute as $attr) {
884 $json[$module]['default'][$attr] = $params[$attr];
885 }
886 }
887 else {
888 $json[$module][$attribute] = $params[$attribute];
889 }
890 }
891 $json = json_encode($json);
892 }
893 else {
894 //if in multilingual state then retrieve the module_data against this contribution and
895 //merge with earlier module_data json data to current so not to lose earlier multilingual module_data information
896 $json = [$module => NULL];
897 foreach ($moduleDataFormat[$module] as $key => $attribute) {
898 if ($key === 'multilingual') {
899 $json[$module][$tsLocale] = [];
900 foreach ($attribute as $attr) {
901 $json[$module][$tsLocale][$attr] = $params[$attr];
902 }
903 }
904 else {
905 $json[$module][$attribute] = $params[$attribute];
906 }
907 }
908
909 $ufJoinDAO = new CRM_Core_DAO_UFJoin();
910 $ufJoinDAO->module = $module;
911 $ufJoinDAO->entity_id = $params['id'];
912 $ufJoinDAO->find(TRUE);
913 $jsonData = json_decode($ufJoinDAO->module_data);
914 if ($jsonData) {
915 $json[$module] = array_merge((array) $jsonData->$module, $json[$module]);
916 }
917 $json = json_encode($json);
918 }
919 return $json;
920 }
921
922 /**
923 * Generate html for pdf in confirmation receipt email attachment.
924 * @param int $contributionId
925 * Contribution Page Id.
926 * @param int $userID
927 * Contact id for contributor.
928 * @return array
929 */
930 public static function addInvoicePdfToEmail($contributionId, $userID) {
931 $contributionID = [$contributionId];
932 $contactId = [$userID];
933 $pdfParams = [
934 'output' => 'pdf_invoice',
935 'forPage' => 'confirmpage',
936 ];
937 $pdfHtml = CRM_Contribute_Form_Task_Invoice::printPDF($contributionID, $pdfParams, $contactId);
938 return $pdfHtml;
939 }
940
941 /**
942 * Helper to determine if the page supports separate membership payments.
943 *
944 * @param int $id form id
945 *
946 * @return bool
947 * isSeparateMembershipPayment
948 */
949 public static function getIsMembershipPayment($id) {
950 $membershipBlocks = civicrm_api3('membership_block', 'get', [
951 'entity_table' => 'civicrm_contribution_page',
952 'entity_id' => $id,
953 'sequential' => TRUE,
954 ]);
955 if (!$membershipBlocks['count']) {
956 return FALSE;
957 }
958 return $membershipBlocks['values'][0]['is_separate_payment'];
959 }
960
961 }