Merge pull request #16759 from eileenmcnaughton/fatal2
[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
18/**
19 * This class contains Contribution Page related functions.
20 */
21class CRM_Contribute_BAO_ContributionPage extends CRM_Contribute_DAO_ContributionPage {
22
23 /**
7bc789a5 24 * Creates a contribution page.
6a488035 25 *
014c4014 26 * @param array $params
6a488035 27 *
16b10e64 28 * @return CRM_Contribute_DAO_ContributionPage
6a488035 29 */
7bc789a5 30 public static function create($params) {
157b21d8 31 $financialTypeId = NULL;
a7488080 32 if (!empty($params['id']) && !CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id'], NULL, 1)) {
157b21d8
PN
33 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $params['id'], 'financial_type_id');
34 }
7bc789a5 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 }
d0a0de8d
EM
39 $hook = empty($params['id']) ? 'create' : 'edit';
40 CRM_Utils_Hook::pre($hook, 'ContributionPage', CRM_Utils_Array::value('id', $params), $params);
6a488035
TO
41 $dao = new CRM_Contribute_DAO_ContributionPage();
42 $dao->copyValues($params);
43 $dao->save();
8cc574cf 44 if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
e1c77163 45 CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_contribution_page', $params['financial_type_id']);
157b21d8 46 }
d0a0de8d 47 CRM_Utils_Hook::post($hook, 'ContributionPage', $dao->id, $dao);
6a488035
TO
48 return $dao;
49 }
50
51 /**
fe482240 52 * Update the is_active flag in the db.
6a488035 53 *
2c4442ca 54 * @deprecated - this bypasses hooks.
55 *
014c4014
TO
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.
6a488035 60 *
8a4fede3 61 * @return bool
62 * true if we found and updated the object, else false
6a488035 63 */
00be9182 64 public static function setIsActive($id, $is_active) {
6a488035
TO
65 return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'is_active', $is_active);
66 }
67
186c9c17 68 /**
2c4442ca 69 * Load values for a contribution page.
70 *
100fef9d 71 * @param int $id
2c4442ca 72 * @param array $values
186c9c17 73 */
00be9182 74 public static function setValues($id, &$values) {
be2fb01f 75 $modules = ['CiviContribute', 'soft_credit', 'on_behalf'];
4779abb3 76 $values['custom_pre_id'] = $values['custom_post_id'] = NULL;
6a488035 77
be2fb01f 78 $params = ['id' => $id];
6a488035 79 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $values);
8ef12e64 80
6a488035 81 // get the profile ids
be2fb01f 82 $ufJoinParams = [
6a488035
TO
83 'entity_table' => 'civicrm_contribution_page',
84 'entity_id' => $id,
be2fb01f 85 ];
6a488035 86
4779abb3 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 }
6a488035 119 }
874c9be7 120 }
6a488035
TO
121
122 /**
fe482240 123 * Send the emails.
6a488035 124 *
014c4014
TO
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.
6a488035 133 *
2c4442ca 134 * @param array $fieldTypes
6a488035 135 */
00be9182 136 public static function sendMail($contactID, $values, $isTest = FALSE, $returnMessageText = FALSE, $fieldTypes = NULL) {
be2fb01f
CW
137 $gIds = [];
138 $params = ['custom_pre_id' => [], 'custom_post_id' => []];
6a488035 139 $email = NULL;
6e10d414 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.
858f7096 144 // Next stage is to remove this & ensure there are no e-notices - ie. all are set before they hit this fn.
be2fb01f 145 $valuesRequiredForTemplate = [
858f7096 146 'customPre',
147 'customPost',
148 'customPre_grouptitle',
149 'customPost_grouptitle',
150 'useForMember',
151 'membership_assign',
152 'amount',
d9924163 153 'receipt_date',
c2358f41 154 'is_pay_later',
be2fb01f 155 ];
858f7096 156
6e10d414 157 foreach ($valuesRequiredForTemplate as $valueRequiredForTemplate) {
158 if (!isset($values[$valueRequiredForTemplate])) {
159 $values[$valueRequiredForTemplate] = NULL;
160 }
161 }
162
6a488035
TO
163 if (isset($values['custom_pre_id'])) {
164 $preProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_pre_id']);
8cc574cf 165 if ($preProfileType == 'Membership' && !empty($values['membership_id'])) {
be2fb01f
CW
166 $params['custom_pre_id'] = [
167 [
6a488035
TO
168 'member_id',
169 '=',
170 $values['membership_id'],
171 0,
172 0,
be2fb01f
CW
173 ],
174 ];
6a488035 175 }
8cc574cf 176 elseif ($preProfileType == 'Contribution' && !empty($values['contribution_id'])) {
be2fb01f
CW
177 $params['custom_pre_id'] = [
178 [
6a488035
TO
179 'contribution_id',
180 '=',
181 $values['contribution_id'],
182 0,
183 0,
be2fb01f
CW
184 ],
185 ];
6a488035
TO
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']);
8cc574cf 193 if ($postProfileType == 'Membership' && !empty($values['membership_id'])) {
be2fb01f
CW
194 $params['custom_post_id'] = [
195 [
6a488035
TO
196 'member_id',
197 '=',
198 $values['membership_id'],
199 0,
200 0,
be2fb01f
CW
201 ],
202 ];
6a488035 203 }
8cc574cf 204 elseif ($postProfileType == 'Contribution' && !empty($values['contribution_id'])) {
be2fb01f
CW
205 $params['custom_post_id'] = [
206 [
6a488035
TO
207 'contribution_id',
208 '=',
209 $values['contribution_id'],
210 0,
211 0,
be2fb01f
CW
212 ],
213 ];
6a488035
TO
214 }
215
216 $gIds['custom_post_id'] = $values['custom_post_id'];
217 }
218
a7488080
CW
219 if (!empty($values['is_for_organization'])) {
220 if (!empty($values['membership_id'])) {
be2fb01f
CW
221 $params['onbehalf_profile'] = [
222 [
6a488035
TO
223 'member_id',
224 '=',
225 $values['membership_id'],
226 0,
227 0,
be2fb01f
CW
228 ],
229 ];
6a488035 230 }
a7488080 231 elseif (!empty($values['contribution_id'])) {
be2fb01f
CW
232 $params['onbehalf_profile'] = [
233 [
6a488035
TO
234 'contribution_id',
235 '=',
236 $values['contribution_id'],
237 0,
238 0,
be2fb01f
CW
239 ],
240 ];
6a488035
TO
241 }
242 }
243
244 //check whether it is a test drive
245 if ($isTest && !empty($params['custom_pre_id'])) {
be2fb01f 246 $params['custom_pre_id'][] = [
6a488035
TO
247 'contribution_test',
248 '=',
249 1,
250 0,
251 0,
be2fb01f 252 ];
6a488035
TO
253 }
254
255 if ($isTest && !empty($params['custom_post_id'])) {
be2fb01f 256 $params['custom_post_id'][] = [
6a488035
TO
257 'contribution_test',
258 '=',
259 1,
260 0,
261 0,
be2fb01f 262 ];
6a488035 263 }
8ef12e64 264
6a488035
TO
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) {
481a74f4 271 $val = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $contactID, CRM_Utils_Array::value($key, $params), TRUE);
6a488035
TO
272 CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
273 }
274 }
275 }
276 }
277
8cc574cf 278 if (!empty($values['is_email_receipt']) || !empty($values['onbehalf_dupe_alert']) ||
6a488035
TO
279 $returnMessageText
280 ) {
281 $template = CRM_Core_Smarty::singleton();
282
283 // get the billing location type
284 if (!array_key_exists('related_contact', $values)) {
b576d770 285 $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
6a488035
TO
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)) {
a7488080 313 if (!empty($values['related_contact'])) {
6a488035 314 $preProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($preID);
da5d91d5 315 if (in_array('Individual', $preProfileTypes) || in_array('Contact', $preProfileTypes)) {
6a488035
TO
316 //Take Individual contact ID
317 $userID = CRM_Utils_Array::value('related_contact', $values);
318 }
319 }
6e10d414 320 list($values['customPre_grouptitle'], $values['customPre']) = self::getProfileNameAndFields($preID, $userID, $params['custom_pre_id']);
6a488035
TO
321 }
322 $userID = $contactID;
323 if ($postID = CRM_Utils_Array::value('custom_post_id', $values)) {
a7488080 324 if (!empty($values['related_contact'])) {
6a488035
TO
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 = CRM_Utils_Array::value('related_contact', $values);
329 }
330 }
6e10d414 331 list($values['customPost_grouptitle'], $values['customPost']) = self::getProfileNameAndFields($postID, $userID, $params['custom_post_id']);
6a488035 332 }
1421174e 333 if (isset($values['honor'])) {
334 $honorValues = $values['honor'];
be2fb01f 335 $template->_values = ['honoree_profile_id' => $values['honoree_profile_id']];
1421174e 336 CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields(
337 $template,
338 $honorValues['honor_profile_values'],
1421174e 339 $honorValues['honor_id']
340 );
341 }
6a488035 342
f56ef33f 343 $title = isset($values['title']) ? $values['title'] : CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($values['contribution_page_id']);
6a488035 344
557e8899 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.
be2fb01f 347 $tplParams = [
6a488035 348 'email' => $email,
6b409353 349 'receiptFromEmail' => $values['receipt_from_email'] ?? NULL,
6a488035
TO
350 'contactID' => $contactID,
351 'displayName' => $displayName,
6b409353
CW
352 'contributionID' => $values['contribution_id'] ?? NULL,
353 'contributionOtherID' => $values['contribution_other_id'] ?? NULL,
6a488035 354 // CRM-5095
6b409353 355 'lineItem' => $values['lineItem'] ?? NULL,
6a488035 356 // CRM-5095
6b409353 357 'priceSetID' => $values['priceSetID'] ?? NULL,
6a488035 358 'title' => $title,
6b409353
CW
359 'isShare' => $values['is_share'] ?? NULL,
360 'thankyou_title' => $values['thankyou_title'] ?? NULL,
6e10d414 361 'customPre' => $values['customPre'],
362 'customPre_grouptitle' => $values['customPre_grouptitle'],
363 'customPost' => $values['customPost'],
364 'customPost_grouptitle' => $values['customPost_grouptitle'],
557e8899 365 'useForMember' => $values['useForMember'],
858f7096 366 'membership_assign' => $values['membership_assign'],
367 'amount' => $values['amount'],
c2358f41 368 'is_pay_later' => $values['is_pay_later'],
76e8d9c4 369 'receipt_date' => !$values['receipt_date'] ? NULL : date('YmdHis', strtotime($values['receipt_date'])),
6b409353
CW
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,
be2fb01f 373 ];
6a488035 374
91bb24a7 375 if ($contributionTypeId = CRM_Utils_Array::value('financial_type_id', $values)) {
b956b310 376 $tplParams['financialTypeId'] = $contributionTypeId;
377 $tplParams['financialTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
91bb24a7 378 $contributionTypeId);
b956b310 379 // Legacy support
380 $tplParams['contributionTypeName'] = $tplParams['financialTypeName'];
381 $tplParams['contributionTypeId'] = $contributionTypeId;
6a488035
TO
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 = CRM_Utils_Array::value('cc_receipt', $values);
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
fdd2a6db 403 //@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used
0d8afee2 404 $values['cc_receipt'] = !empty($values['cc_receipt']) ? ($values['cc_receipt'] . ',' . $ccMailId) : $ccMailId;
6a488035
TO
405
406 // reset primary-email in the template
407 $tplParams['email'] = $ccEmail;
408
409 $tplParams['onBehalfName'] = $displayName;
410 $tplParams['onBehalfEmail'] = $email;
411
4779abb3 412 if (!empty($values['onbehalf_profile_id'])) {
413 self::buildCustomDisplay($values['onbehalf_profile_id'], 'onBehalfProfile', $contactID, $template, $params['onbehalf_profile'], $fieldTypes);
414 }
6a488035
TO
415 }
416
417 // use either the contribution or membership receipt, based on whether it’s a membership-related contrib or not
be2fb01f 418 $sendTemplateParams = [
12dac866 419 'groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
420 'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt',
6a488035
TO
421 'contactId' => $contactID,
422 'tplParams' => $tplParams,
423 'isTest' => $isTest,
424 'PDFFilename' => 'receipt.pdf',
be2fb01f 425 ];
6a488035
TO
426
427 if ($returnMessageText) {
c6327d7d 428 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
be2fb01f 429 return [
6a488035
TO
430 'subject' => $subject,
431 'body' => $message,
432 'to' => $displayName,
433 'html' => $html,
be2fb01f 434 ];
6a488035
TO
435 }
436
ec7e3954
E
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
6a488035
TO
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'] = CRM_Utils_Array::value('cc_receipt', $values);
446 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
9161952c 447 //send email with pdf invoice
481a74f4 448 $template = CRM_Core_Smarty::singleton();
9161952c 449 $taxAmt = $template->get_template_vars('dataArray');
aaffa79f 450 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
9161952c 451 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
121bf42c 452 if (isset($invoicing) && isset($prefixValue['is_email_pdf'])) {
874c9be7 453 $sendTemplateParams['isEmailPdf'] = TRUE;
9161952c
PD
454 $sendTemplateParams['contributionId'] = $values['contribution_id'];
455 }
c6327d7d 456 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
457 }
458
459 // send duplicate alert, if dupe match found during on-behalf-of processing.
a7488080 460 if (!empty($values['onbehalf_dupe_alert'])) {
6a488035
TO
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'] = CRM_Utils_Array::value('receipt_from_name', $values);
465 $sendTemplateParams['toEmail'] = CRM_Utils_Array::value('receipt_from_email', $values);
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
c6327d7d 472 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
473 }
474 }
475 }
8ef12e64 476
6e10d414 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 */
be2fb01f 487 protected static function getProfileNameAndFields($gid, $cid, &$params, $fieldTypes = []) {
6e10d414 488 $groupTitle = NULL;
be2fb01f 489 $values = [];
6e10d414 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 }
be2fb01f 514 return [$groupTitle, $values];
6e10d414 515 }
516
186c9c17 517 /**
84f0ed41 518 * Send the emails for Recurring Contribution Notification.
6a488035 519 *
014c4014
TO
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.
2a6da8d7 528 * @param bool|object $autoRenewMembership is it a auto renew membership.
6a488035 529 */
00be9182 530 public static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE) {
be2fb01f 531 $value = [];
ddf80fb9 532 $isEmailReceipt = FALSE;
6a488035 533 if ($pageID) {
be2fb01f 534 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, [
91bb24a7 535 'title',
536 'is_email_receipt',
537 'receipt_from_name',
538 'receipt_from_email',
539 'cc_receipt',
540 'bcc_receipt',
be2fb01f 541 ]);
ab30e033 542 $isEmailReceipt = CRM_Utils_Array::value('is_email_receipt', $value[$pageID]);
6a488035 543 }
ab30e033
EM
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;
6a488035 548 }
ab30e033
EM
549
550 if ($isEmailReceipt) {
6a488035
TO
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 {
91bb24a7 558 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
559 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
560 $receiptFromName = $domainValues[0];
6a488035
TO
561 $receiptFromEmail = $domainValues[1];
562 }
563
564 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE);
be2fb01f 565 $templatesParams = [
6a488035
TO
566 'groupName' => 'msg_tpl_workflow_contribution',
567 'valueName' => 'contribution_recurring_notify',
568 'contactId' => $contactID,
be2fb01f 569 'tplParams' => [
6a488035
TO
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,
be2fb01f 581 ],
6a488035
TO
582 'from' => $receiptFrom,
583 'toName' => $displayName,
584 'toEmail' => $email,
be2fb01f 585 ];
1421174e 586 //CRM-13811
039134ba 587 if ($pageID) {
588 $templatesParams['cc'] = CRM_Utils_Array::value('cc_receipt', $value[$pageID]);
589 $templatesParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $value[$pageID]);
590 }
6a488035
TO
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.
91bb24a7 594 $template = CRM_Core_Smarty::singleton();
6a488035 595 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
3e473c0b 596 $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'cancel');
6a488035
TO
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
84f0ed41 606 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
6a488035
TO
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 /**
c7e7164f 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.
6a488035 624 *
014c4014
TO
625 * @param int $gid
626 * Uf group id.
6a488035 627 * @param string $name
014c4014
TO
628 * @param int $cid
629 * Contact id.
2a6da8d7 630 * @param $template
014c4014
TO
631 * @param array $params
632 * Params to build component whereclause.
2a6da8d7 633 *
6e10d414 634 * @param array|null $fieldTypes
6a488035 635 */
6e10d414 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);
6a488035 640 }
6e10d414 641 $template->assign($name . "_grouptitle", $groupTitle);
6a488035
TO
642 }
643
644 /**
2c4442ca 645 * Make a copy of a contribution page, including all the blocks in the page.
6a488035 646 *
014c4014
TO
647 * @param int $id
648 * The contribution page id to copy.
6a488035 649 *
72b3a70c 650 * @return CRM_Contribute_DAO_ContributionPage
6a488035 651 */
00be9182 652 public static function copy($id) {
e6df7827
J
653 $session = CRM_Core_Session::singleton();
654
be2fb01f
CW
655 $fieldsFix = [
656 'prefix' => [
6a488035 657 'title' => ts('Copy of') . ' ',
be2fb01f 658 ],
e6df7827
J
659 'replace' => [
660 'created_id' => $session->get('userID'),
661 'created_date' => date('YmdHis'),
662 ],
be2fb01f 663 ];
3fec1adc 664 $copy = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', [
353ffa53 665 'id' => $id,
be2fb01f 666 ], NULL, $fieldsFix);
6a488035
TO
667
668 //copying all the blocks pertaining to the contribution page
3fec1adc 669 $copyPledgeBlock = CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', [
353ffa53
TO
670 'entity_id' => $id,
671 'entity_table' => 'civicrm_contribution_page',
be2fb01f 672 ], [
353ffa53 673 'entity_id' => $copy->id,
be2fb01f 674 ]);
6a488035 675
3fec1adc 676 $copyMembershipBlock = CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', [
353ffa53
TO
677 'entity_id' => $id,
678 'entity_table' => 'civicrm_contribution_page',
be2fb01f 679 ], [
353ffa53 680 'entity_id' => $copy->id,
be2fb01f 681 ]);
6a488035 682
3fec1adc 683 $copyUFJoin = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', [
353ffa53
TO
684 'entity_id' => $id,
685 'entity_table' => 'civicrm_contribution_page',
be2fb01f 686 ], [
353ffa53 687 'entity_id' => $copy->id,
be2fb01f 688 ]);
6a488035 689
3fec1adc 690 $copyWidget = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', [
353ffa53 691 'contribution_page_id' => $id,
be2fb01f 692 ], [
353ffa53 693 'contribution_page_id' => $copy->id,
be2fb01f 694 ]);
6a488035 695
c6914066 696 //copy price sets
9da8dc8c 697 CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_contribution_page', $id, $copy->id);
c6914066 698
3fec1adc 699 $copyTellFriend = CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', [
353ffa53
TO
700 'entity_id' => $id,
701 'entity_table' => 'civicrm_contribution_page',
be2fb01f 702 ], [
353ffa53 703 'entity_id' => $copy->id,
be2fb01f 704 ]);
6a488035 705
3fec1adc 706 $copyPersonalCampaignPages = CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', [
353ffa53
TO
707 'entity_id' => $id,
708 'entity_table' => 'civicrm_contribution_page',
be2fb01f 709 ], [
353ffa53 710 'entity_id' => $copy->id,
b7ff0a0a 711 'target_entity_id' => $copy->id,
be2fb01f 712 ]);
6a488035 713
3fec1adc 714 $copyPremium = CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', [
353ffa53
TO
715 'entity_id' => $id,
716 'entity_table' => 'civicrm_contribution_page',
be2fb01f 717 ], [
353ffa53 718 'entity_id' => $copy->id,
be2fb01f 719 ]);
6a488035
TO
720 $premiumQuery = "
721SELECT id
722FROM civicrm_premiums
723WHERE entity_table = 'civicrm_contribution_page'
724 AND entity_id ={$id}";
725
e03e1641 726 $premiumDao = CRM_Core_DAO::executeQuery($premiumQuery);
6a488035
TO
727 while ($premiumDao->fetch()) {
728 if ($premiumDao->id) {
be2fb01f 729 CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', [
91bb24a7 730 'premiums_id' => $premiumDao->id,
be2fb01f 731 ], [
91bb24a7 732 'premiums_id' => $copyPremium->id,
be2fb01f 733 ]);
6a488035
TO
734 }
735 }
736
737 $copy->save();
738
739 CRM_Utils_Hook::copy('ContributionPage', $copy);
740
741 return $copy;
742 }
743
6a488035 744 /**
100fef9d 745 * Get info for all sections enable/disable.
6a488035 746 *
2a6da8d7 747 * @param array $contribPageIds
a6c01b45
CW
748 * @return array
749 * info regarding all sections.
6a488035 750 */
be2fb01f
CW
751 public static function getSectionInfo($contribPageIds = []) {
752 $info = [];
6a488035
TO
753 $whereClause = NULL;
754 if (is_array($contribPageIds) && !empty($contribPageIds)) {
755 $whereClause = 'WHERE civicrm_contribution_page.id IN ( ' . implode(', ', $contribPageIds) . ' )';
756 }
757
be2fb01f 758 $sections = [
6a488035
TO
759 'settings',
760 'amount',
761 'membership',
762 'custom',
763 'thankyou',
764 'friend',
765 'pcp',
766 'widget',
767 'premium',
be2fb01f 768 ];
6a488035
TO
769 $query = "
770 SELECT civicrm_contribution_page.id as id,
8ef12e64 771 civicrm_contribution_page.financial_type_id as settings,
6a488035
TO
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
781LEFT 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 )
784LEFT 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 )
788LEFT 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)
791LEFT 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 )
794LEFT JOIN civicrm_contribution_widget ON ( civicrm_contribution_widget.contribution_page_id = civicrm_contribution_page.id
795 AND civicrm_contribution_widget.is_active = 1 )
796LEFT 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 }
e1462487
CW
815
816 /**
817 * Get options for a given field.
818 * @see CRM_Core_DAO::buildOptions
819 *
014c4014 820 * @param string $fieldName
353ffa53
TO
821 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
822 * @param array $props : whatever is known about this dao object
e1462487
CW
823 *
824 * @return array|bool
825 */
be2fb01f
CW
826 public static function buildOptions($fieldName, $context = NULL, $props = []) {
827 $params = [];
e1462487
CW
828 // Special logic for fields whose options depend on context or properties
829 switch ($fieldName) {
830 case 'financial_type_id':
341a4d71
MW
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 [];
e1462487
CW
838 }
839 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
840 }
ba60f73e 841
842 /**
e63910c5 843 * Get or Set honor/on_behalf params for processing module_data or setting default values.
ba60f73e 844 *
e63910c5 845 * @param array $params :
353ffa53 846 * @param bool $setDefault : If yes then returns array to used for setting default value afterward
e63910c5 847 * @param string $module : processing module_data for which module? e.g. soft_credit, on_behalf
ba60f73e 848 *
849 * @return array|string
850 */
e63910c5 851 public static function formatModuleData($params, $setDefault = FALSE, $module) {
98466ff9 852 $tsLocale = CRM_Core_I18n::getLocale();
ba60f73e 853 $config = CRM_Core_Config::singleton();
e63910c5 854 $json = $jsonDecode = NULL;
ba60f73e 855 $domain = new CRM_Core_DAO_Domain();
856 $domain->find(TRUE);
857
be2fb01f
CW
858 $moduleDataFormat = [
859 'soft_credit' => [
f23093b2 860 1 => 'soft_credit_types',
be2fb01f 861 'multilingual' => [
e63910c5 862 'honor_block_title',
cb804cd9 863 'honor_block_text',
be2fb01f
CW
864 ],
865 ],
866 'on_behalf' => [
f23093b2 867 1 => 'is_for_organization',
be2fb01f 868 'multilingual' => [
f23093b2 869 'for_organization',
be2fb01f
CW
870 ],
871 ],
872 ];
e63910c5 873
12792976 874 //When we are fetching the honor params respecting both multi and mono lingual state
ba60f73e 875 //and setting it to default param of Contribution Page's Main and Setting form
876 if ($setDefault) {
e63910c5 877 $jsonDecode = json_decode($params);
878 $jsonDecode = (array) $jsonDecode->$module;
879 if (!$domain->locales && !empty($jsonDecode['default'])) {
12792976 880 //monolingual state
e63910c5 881 $jsonDecode += (array) $jsonDecode['default'];
882 unset($jsonDecode['default']);
12792976 883 }
d50cdfb5 884 elseif (!empty($jsonDecode[$tsLocale])) {
12792976 885 //multilingual state
d50cdfb5 886 foreach ($jsonDecode[$tsLocale] as $column => $value) {
e63910c5 887 $jsonDecode[$column] = $value;
ba60f73e 888 }
d50cdfb5 889 unset($jsonDecode[$tsLocale]);
ba60f73e 890 }
e63910c5 891 return $jsonDecode;
ba60f73e 892 }
893
894 //check and handle multilingual honoree params
895 if (!$domain->locales) {
896 //if in singlelingual state simply return the array format
be2fb01f 897 $json = [$module => NULL];
e63910c5 898 foreach ($moduleDataFormat[$module] as $key => $attribute) {
899 if ($key === 'multilingual') {
be2fb01f 900 $json[$module]['default'] = [];
e63910c5 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);
ba60f73e 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
be2fb01f 914 $json = [$module => NULL];
e63910c5 915 foreach ($moduleDataFormat[$module] as $key => $attribute) {
916 if ($key === 'multilingual') {
be2fb01f 917 $json[$module][$config->lcMessages] = [];
e63910c5 918 foreach ($attribute as $attr) {
919 $json[$module][$config->lcMessages][$attr] = $params[$attr];
920 }
921 }
922 else {
923 $json[$module][$attribute] = $params[$attribute];
d1f8e278 924 }
d1f8e278 925 }
d1f8e278 926
927 $ufJoinDAO = new CRM_Core_DAO_UFJoin();
e63910c5 928 $ufJoinDAO->module = $module;
d1f8e278 929 $ufJoinDAO->entity_id = $params['id'];
930 $ufJoinDAO->find(TRUE);
931 $jsonData = json_decode($ufJoinDAO->module_data);
932 if ($jsonData) {
e63910c5 933 $json[$module] = array_merge((array) $jsonData->$module, $json[$module]);
d1f8e278 934 }
e63910c5 935 $json = json_encode($json);
d1f8e278 936 }
e63910c5 937 return $json;
d1f8e278 938 }
939
940 /**
941 * Generate html for pdf in confirmation receipt email attachment.
014c4014
TO
942 * @param int $contributionId
943 * Contribution Page Id.
944 * @param int $userID
945 * Contact id for contributor.
a6c01b45 946 * @return array
9161952c 947 */
00be9182 948 public static function addInvoicePdfToEmail($contributionId, $userID) {
be2fb01f
CW
949 $contributionID = [$contributionId];
950 $contactId = [$userID];
951 $pdfParams = [
9161952c 952 'output' => 'pdf_invoice',
21dfd5f5 953 'forPage' => 'confirmpage',
be2fb01f 954 ];
1273d77c 955 $pdfHtml = CRM_Contribute_Form_Task_Invoice::printPDF($contributionID, $pdfParams, $contactId);
9161952c
PD
956 return $pdfHtml;
957 }
f64a217a
EM
958
959 /**
7fe37828
EM
960 * Helper to determine if the page supports separate membership payments.
961 *
79d7553f 962 * @param int $id form id
f64a217a 963 *
a6c01b45
CW
964 * @return bool
965 * isSeparateMembershipPayment
f64a217a 966 */
00be9182 967 public static function getIsMembershipPayment($id) {
be2fb01f 968 $membershipBlocks = civicrm_api3('membership_block', 'get', [
1330f57a
SL
969 'entity_table' => 'civicrm_contribution_page',
970 'entity_id' => $id,
971 'sequential' => TRUE,
972 ]);
22e263ad 973 if (!$membershipBlocks['count']) {
f64a217a
EM
974 return FALSE;
975 }
976 return $membershipBlocks['values'][0]['is_separate_payment'];
977 }
96025800 978
6a488035 979}