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