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