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