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