Merge pull request #17981 from eileenmcnaughton/merge_form
[civicrm-core.git] / CRM / PCP / BAO / PCP.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 class CRM_PCP_BAO_PCP extends CRM_PCP_DAO_PCP {
18
19 /**
20 * The action links that we need to display for the browse screen.
21 *
22 * @var array
23 */
24 public static $_pcpLinks = NULL;
25
26 /**
27 * Class constructor.
28 */
29 public function __construct() {
30 parent::__construct();
31 }
32
33 /**
34 * Add or update either a Personal Campaign Page OR a PCP Block.
35 *
36 * @param array $params
37 * Values to create the pcp.
38 *
39 * @return object
40 */
41 public static function create($params) {
42
43 $dao = new CRM_PCP_DAO_PCP();
44 $dao->copyValues($params);
45
46 // ensure we set status_id since it is a not null field
47 // we should change the schema and allow this to be null
48 if (!$dao->id && !isset($dao->status_id)) {
49 $dao->status_id = 0;
50 }
51
52 // set currency for CRM-1496
53 if (!isset($dao->currency)) {
54 $dao->currency = CRM_Core_Config::singleton()->defaultCurrency;
55 }
56
57 $dao->save();
58 return $dao;
59 }
60
61 /**
62 * Get the Display name of a contact for a PCP.
63 *
64 * @param int $id
65 * Id for the PCP.
66 *
67 * @return null|string
68 * Display name of the contact if found
69 */
70 public static function displayName($id) {
71 $id = CRM_Utils_Type::escape($id, 'Integer');
72
73 $query = "
74 SELECT civicrm_contact.display_name
75 FROM civicrm_pcp, civicrm_contact
76 WHERE civicrm_pcp.contact_id = civicrm_contact.id
77 AND civicrm_pcp.id = {$id}
78 ";
79 return CRM_Core_DAO::singleValueQuery($query);
80 }
81
82 /**
83 * Return PCP Block info for dashboard.
84 *
85 * @param int $contactId
86 *
87 * @return array
88 * array of Pcp if found
89 */
90 public static function getPcpDashboardInfo($contactId) {
91 $links = self::pcpLinks();
92
93 $query = '
94 SELECT pcp.*, block.is_tellfriend_enabled FROM civicrm_pcp pcp
95 LEFT JOIN civicrm_pcp_block block ON block.id = pcp.pcp_block_id
96 WHERE pcp.is_active = 1
97 AND pcp.contact_id = %1
98 ORDER BY page_type, page_id';
99
100 $params = [1 => [$contactId, 'Integer']];
101
102 $pcpInfoDao = CRM_Core_DAO::executeQuery($query, $params);
103 $pcpInfo = [];
104 $hide = $mask = array_sum(array_keys($links['all']));
105 $contactPCPPages = [];
106
107 $approved = CRM_Core_PseudoConstant::getKey('CRM_PCP_BAO_PCP', 'status_id', 'Approved');
108
109 while ($pcpInfoDao->fetch()) {
110 $mask = $hide;
111 if ($links) {
112 $replace = [
113 'pcpId' => $pcpInfoDao->id,
114 'pcpBlock' => $pcpInfoDao->pcp_block_id,
115 'pageComponent' => $pcpInfoDao->page_type,
116 ];
117 }
118
119 $pcpLink = $links['all'];
120 $class = '';
121
122 if ($pcpInfoDao->status_id != $approved || $pcpInfoDao->is_active != 1) {
123 $class = 'disabled';
124 if (!$pcpInfoDao->is_tellfriend_enabled) {
125 $mask -= CRM_Core_Action::DETACH;
126 }
127 }
128
129 if ($pcpInfoDao->is_active == 1) {
130 $mask -= CRM_Core_Action::ENABLE;
131 }
132 else {
133 $mask -= CRM_Core_Action::DISABLE;
134 }
135 $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'),
136 FALSE, 'pcp.dashboard.active', 'PCP', $pcpInfoDao->id);
137
138 $pageTitle = self::getPcpTitle($pcpInfoDao->page_type, (int) $pcpInfoDao->page_id);
139
140 $pcpInfo[] = [
141 'pageTitle' => $pageTitle,
142 'pcpId' => $pcpInfoDao->id,
143 'pcpTitle' => $pcpInfoDao->title,
144 'pcpStatus' => CRM_Core_PseudoConstant::getLabel('CRM_PCP_BAO_PCP', 'status_id', $pcpInfoDao->status_id),
145 'action' => $action,
146 'class' => $class,
147 ];
148 $contactPCPPages[$pcpInfoDao->page_type][] = $pcpInfoDao->page_id;
149 }
150
151 $excludePageClause = $clause = NULL;
152 if (!empty($contactPCPPages)) {
153 foreach ($contactPCPPages as $component => $entityIds) {
154 $excludePageClause[] = "
155 ( target_entity_type = '{$component}'
156 AND target_entity_id NOT IN ( " . implode(',', $entityIds) . ") )";
157 }
158
159 $clause = ' AND ' . implode(' OR ', $excludePageClause);
160 }
161
162 $query = "
163 SELECT *
164 FROM civicrm_pcp_block block
165 LEFT JOIN civicrm_pcp pcp ON pcp.pcp_block_id = block.id
166 WHERE block.is_active = 1
167 {$clause}
168 GROUP BY block.id, pcp.id
169 ORDER BY target_entity_type, target_entity_id
170 ";
171 $pcpBlockDao = CRM_Core_DAO::executeQuery($query);
172 $pcpBlock = [];
173 $mask = 0;
174
175 while ($pcpBlockDao->fetch()) {
176 if ($links) {
177 $replace = [
178 'pageId' => $pcpBlockDao->target_entity_id,
179 'pageComponent' => $pcpBlockDao->target_entity_type,
180 ];
181 }
182 $pcpLink = $links['add'];
183 $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'),
184 FALSE, 'pcp.dashboard.other', "{$pcpBlockDao->target_entity_type}_PCP", $pcpBlockDao->target_entity_id);
185 $pageTitle = self::getPcpTitle($pcpBlockDao->target_entity_type, (int) $pcpBlockDao->target_entity_id);
186 if ($pageTitle) {
187 $pcpBlock[] = [
188 'pageId' => $pcpBlockDao->target_entity_id,
189 'pageTitle' => $pageTitle,
190 'action' => $action,
191 ];
192 }
193 }
194
195 return [$pcpBlock, $pcpInfo];
196 }
197
198 /**
199 * Show the total amount for Personal Campaign Page on thermometer.
200 *
201 * @param array $pcpId
202 * Contains the pcp ID.
203 *
204 * @return float
205 * Total amount
206 */
207 public static function thermoMeter($pcpId) {
208 $completedStatusId = CRM_Core_PseudoConstant::getKey(
209 'CRM_Contribute_BAO_Contribution',
210 'contribution_status_id',
211 'Completed'
212 );
213 $query = "
214 SELECT SUM(cc.total_amount) as total
215 FROM civicrm_pcp pcp
216 LEFT JOIN civicrm_contribution_soft cs ON ( pcp.id = cs.pcp_id )
217 LEFT JOIN civicrm_contribution cc ON ( cs.contribution_id = cc.id)
218 WHERE pcp.id = %1 AND cc.contribution_status_id = %2 AND cc.is_test = 0";
219
220 $params = [
221 1 => [$pcpId, 'Integer'],
222 2 => [$completedStatusId, 'Integer'],
223 ];
224 return CRM_Core_DAO::singleValueQuery($query, $params);
225 }
226
227 /**
228 * Show the amount, nickname on honor roll.
229 *
230 * @param array $pcpId
231 * Contains the pcp ID.
232 *
233 * @return array
234 */
235 public static function honorRoll($pcpId) {
236 $completedStatusId = CRM_Core_PseudoConstant::getKey(
237 'CRM_Contribute_BAO_Contribution',
238 'contribution_status_id',
239 'Completed'
240 );
241 $query = "
242 SELECT cc.id, cs.pcp_roll_nickname, cs.pcp_personal_note,
243 cc.total_amount, cc.currency
244 FROM civicrm_contribution cc
245 LEFT JOIN civicrm_contribution_soft cs ON cc.id = cs.contribution_id
246 WHERE cs.pcp_id = %1
247 AND cs.pcp_display_in_roll = 1
248 AND contribution_status_id = %2
249 AND is_test = 0";
250 $params = [
251 1 => [$pcpId, 'Integer'],
252 2 => [$completedStatusId, 'Integer'],
253 ];
254 $dao = CRM_Core_DAO::executeQuery($query, $params);
255 $honor = [];
256 while ($dao->fetch()) {
257 $honor[$dao->id]['nickname'] = ucwords($dao->pcp_roll_nickname);
258 $honor[$dao->id]['total_amount'] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
259 $honor[$dao->id]['personal_note'] = $dao->pcp_personal_note;
260 }
261 return $honor;
262 }
263
264 /**
265 * Get action links.
266 *
267 * @return array
268 * (reference) of action links
269 */
270 public static function &pcpLinks() {
271 if (!(self::$_pcpLinks)) {
272 $deleteExtra = ts('Are you sure you want to delete this Personal Campaign Page?') . '\n' . ts('This action cannot be undone.');
273
274 self::$_pcpLinks['add'] = [
275 CRM_Core_Action::ADD => [
276 'name' => ts('Create a Personal Campaign Page'),
277 'class' => 'no-popup',
278 'url' => 'civicrm/contribute/campaign',
279 'qs' => 'action=add&reset=1&pageId=%%pageId%%&component=%%pageComponent%%',
280 'title' => ts('Configure'),
281 ],
282 ];
283
284 self::$_pcpLinks['all'] = [
285 CRM_Core_Action::UPDATE => [
286 'name' => ts('Edit Your Page'),
287 'url' => 'civicrm/pcp/info',
288 'qs' => 'action=update&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
289 'title' => ts('Configure'),
290 ],
291 CRM_Core_Action::DETACH => [
292 'name' => ts('Tell Friends'),
293 'url' => 'civicrm/friend',
294 'qs' => 'eid=%%pcpId%%&blockId=%%pcpBlock%%&reset=1&pcomponent=pcp&component=%%pageComponent%%',
295 'title' => ts('Tell Friends'),
296 ],
297 CRM_Core_Action::VIEW => [
298 'name' => ts('URL for this Page'),
299 'url' => 'civicrm/pcp/info',
300 'qs' => 'reset=1&id=%%pcpId%%&component=%%pageComponent%%',
301 'title' => ts('URL for this Page'),
302 ],
303 CRM_Core_Action::BROWSE => [
304 'name' => ts('Update Contact Information'),
305 'url' => 'civicrm/pcp/info',
306 'qs' => 'action=browse&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
307 'title' => ts('Update Contact Information'),
308 ],
309 CRM_Core_Action::ENABLE => [
310 'name' => ts('Enable'),
311 'url' => 'civicrm/pcp',
312 'qs' => 'action=enable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
313 'title' => ts('Enable'),
314 ],
315 CRM_Core_Action::DISABLE => [
316 'name' => ts('Disable'),
317 'url' => 'civicrm/pcp',
318 'qs' => 'action=disable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
319 'title' => ts('Disable'),
320 ],
321 CRM_Core_Action::DELETE => [
322 'name' => ts('Delete'),
323 'url' => 'civicrm/pcp',
324 'qs' => 'action=delete&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
325 'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
326 'title' => ts('Delete'),
327 ],
328 ];
329 }
330 return self::$_pcpLinks;
331 }
332
333 /**
334 * Delete the campaign page.
335 *
336 * @param int $id
337 * Campaign page id.
338 */
339 public static function deleteById($id) {
340 CRM_Utils_Hook::pre('delete', 'Campaign', $id, CRM_Core_DAO::$_nullArray);
341
342 $transaction = new CRM_Core_Transaction();
343
344 // delete from pcp table
345 $pcp = new CRM_PCP_DAO_PCP();
346 $pcp->id = $id;
347 $pcp->delete();
348
349 $transaction->commit();
350
351 CRM_Utils_Hook::post('delete', 'Campaign', $id, $pcp);
352 }
353
354 /**
355 * Build the form object.
356 *
357 * @param CRM_Core_Form $form
358 * Form object.
359 */
360 public static function buildPCPForm($form) {
361 $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"]);
362
363 $form->addElement('checkbox', 'is_approval_needed', ts('Approval required'));
364
365 $profile = [];
366 $isUserRequired = NULL;
367 $config = CRM_Core_Config::singleton();
368 if ($config->userFramework != 'Standalone') {
369 $isUserRequired = 2;
370 }
371 CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, [
372 'title',
373 'is_active',
374 ]);
375 if (!empty($profiles)) {
376 foreach ($profiles as $key => $value) {
377 if ($value['is_active']) {
378 $profile[$key] = $value['title'];
379 }
380 }
381 $form->assign('profile', $profile);
382 }
383
384 $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), ['' => ts('- select -')] + $profile, TRUE);
385
386 //CRM-15821 - To add new option for PCP "Owner" notification
387 $ownerNotifications = CRM_Core_OptionGroup::values('pcp_owner_notify');
388 $form->addRadio('owner_notify_id', ts('Owner Email Notification'), $ownerNotifications, NULL, '<br/>', TRUE);
389
390 $form->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), NULL, ['onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"]);
391
392 $form->add('number',
393 'tellfriend_limit',
394 ts("'Tell a friend' maximum recipients limit"),
395 CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'tellfriend_limit')
396 );
397 $form->addRule('tellfriend_limit', ts('Please enter a valid limit.'), 'integer');
398
399 $form->add('text',
400 'link_text',
401 ts("'Create Personal Campaign Page' link text"),
402 CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'link_text')
403 );
404
405 $form->add('text', 'notify_email', ts('Notify Email'), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'notify_email'));
406 }
407
408 /**
409 * This function builds the supporter text for the pcp
410 *
411 * @param int $pcpID
412 * the personal campaign page ID
413 * @param int $contributionPageID
414 * @param string $component
415 * one of 'contribute' or 'event'
416 *
417 * @return string
418 */
419 public static function getPcpSupporterText($pcpID, $contributionPageID, $component) {
420 $pcp_supporter_text = '';
421 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($contributionPageID, $component);
422 $pcpSupporter = CRM_PCP_BAO_PCP::displayName($pcpID);
423 switch ($component) {
424 case 'event':
425 $pcp_supporter_text = ts('This event registration is being made thanks to the efforts of <strong>%1</strong>, who supports our campaign. ', [1 => $pcpSupporter]);
426 if (!empty($text)) {
427 $pcp_supporter_text .= ts('You can support it as well - once you complete the registration, you will be able to create your own Personal Campaign Page!');
428 }
429 break;
430
431 case 'contribute':
432 $pcp_supporter_text = ts('This contribution is being made thanks to the efforts of <strong>%1</strong>, who supports our campaign. ', [1 => $pcpSupporter]);
433 if (!empty($text)) {
434 $pcp_supporter_text .= ts('You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!');
435 }
436 break;
437 }
438 return $pcp_supporter_text;
439 }
440
441 /**
442 * Add PCP form elements to a form.
443 *
444 * @param int $pcpId
445 * @param CRM_Core_Form $page
446 * @param array $elements
447 *
448 * @throws \CiviCRM_API3_Exception
449 */
450 public static function buildPcp($pcpId, &$page, &$elements = NULL) {
451 $prms = ['id' => $pcpId];
452 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
453
454 if (CRM_PCP_BAO_PCP::displayName($pcpId)) {
455 $pcp_supporter_text = self::getPcpSupporterText($pcpId, $pcpInfo['page_id'], $pcpInfo['page_type']);
456 $page->assign('pcpSupporterText', $pcp_supporter_text);
457 }
458 $page->assign('pcp', TRUE);
459
460 // build honor roll fields for registration form if supporter has honor roll enabled for their PCP
461 if ($pcpInfo['is_honor_roll']) {
462 $page->assign('is_honor_roll', TRUE);
463 $page->add('checkbox', 'pcp_display_in_roll', ts('Show my support in the public honor roll'), NULL, NULL,
464 ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
465 );
466 $extraOption = ['onclick' => "return pcpAnonymous( );"];
467 $page->addRadio('pcp_is_anonymous', '', [ts('Include my name and message'), ts('List my support anonymously')], [], '&nbsp;&nbsp;&nbsp;', FALSE, [$extraOption, $extraOption]);
468 $page->_defaults['pcp_is_anonymous'] = 0;
469
470 $page->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
471 $page->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
472 }
473 else {
474 $page->assign('is_honor_roll', FALSE);
475 }
476 }
477
478 /**
479 * Process a PCP contribution.
480 *
481 * @param int $pcpId
482 * @param string $component
483 * @param string $entity
484 *
485 * @return array
486 */
487 public static function handlePcp($pcpId, $component, $entity) {
488
489 self::getPcpEntityTable($component);
490
491 if (!$pcpId) {
492 return FALSE;
493 }
494
495 $pcpStatus = CRM_Core_PseudoConstant::get('CRM_PCP_BAO_PCP', 'status_id');
496 $approvedId = array_search('Approved', $pcpStatus);
497
498 $params = ['id' => $pcpId];
499 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
500
501 $params = ['id' => $pcpInfo['pcp_block_id']];
502 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlock);
503
504 $params = ['id' => $pcpInfo['page_id']];
505 $now = time();
506
507 if ($component == 'event') {
508 // figure out where to redirect if an exception occurs below based on target entity
509 $urlBase = 'civicrm/event/register';
510
511 // ignore startDate for events - PCP's can be active long before event start date
512 $startDate = 0;
513 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity));
514 }
515 elseif ($component == 'contribute') {
516 $urlBase = 'civicrm/contribute/transact';
517 //start and end date of the contribution page
518 $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('start_date', $entity));
519 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity));
520 }
521
522 // define redirect url back to contrib page or event if needed
523 $url = CRM_Utils_System::url($urlBase, "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE);
524 $currentPCPStatus = CRM_Core_PseudoConstant::getName('CRM_PCP_BAO_PCP', 'status_id', $pcpInfo['status_id']);
525
526 if ($pcpBlock['target_entity_id'] != $entity['id']) {
527 $statusMessage = ts('This page is not related to the Personal Campaign Page you have just visited. However you can still make a contribution here.');
528 CRM_Core_Error::statusBounce($statusMessage, $url);
529 }
530 elseif ($currentPCPStatus !== 'Approved') {
531 $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign here.', [1 => $pcpStatus[$pcpInfo['status_id']]]);
532 CRM_Core_Error::statusBounce($statusMessage, $url);
533 }
534 elseif (empty($pcpBlock['is_active'])) {
535 $statusMessage = ts('Personal Campaign Pages are currently not enabled for this contribution page. However you can still support the campaign here.');
536 CRM_Core_Error::statusBounce($statusMessage, $url);
537 }
538 elseif (empty($pcpInfo['is_active'])) {
539 $statusMessage = ts('The Personal Campaign Page you have just visited is currently inactive. However you can still support the campaign here.');
540 CRM_Core_Error::statusBounce($statusMessage, $url);
541 }
542 // Check if we're in range for contribution page start and end dates. for events, check if after event end date
543 elseif (($startDate && $startDate > $now) || ($endDate && $endDate < $now)) {
544 $customStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $entity));
545 $customEndDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $entity));
546 if ($startDate && $endDate) {
547 $statusMessage = ts('The Personal Campaign Page you have just visited is only active from %1 to %2. However you can still support the campaign here.',
548 [1 => $customStartDate, 2 => $customEndDate]
549 );
550 CRM_Core_Error::statusBounce($statusMessage, $url);
551 }
552 elseif ($startDate) {
553 $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign here.', [1 => $customStartDate]);
554 CRM_Core_Error::statusBounce($statusMessage, $url);
555 }
556 elseif ($endDate) {
557 if ($component == 'event') {
558 // Target_entity is an event and the event is over, redirect to event info instead of event registration page.
559 $url = CRM_Utils_System::url('civicrm/event/info',
560 "reset=1&id={$pcpBlock['entity_id']}",
561 FALSE, NULL, FALSE, TRUE
562 );
563 $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', [1 => $customEndDate]);
564 CRM_Core_Error::statusBounce($statusMessage, $url);
565 }
566 else {
567 $statusMessage = ts('The Personal Campaign Page you have just visited is no longer active (as of %1). However you can still support the campaign here.', [1 => $customEndDate]);
568 CRM_Core_Error::statusBounce($statusMessage, $url);
569 }
570 }
571 }
572
573 return [
574 'pcpId' => $pcpId,
575 'pcpBlock' => $pcpBlock,
576 'pcpInfo' => $pcpInfo,
577 ];
578 }
579
580 /**
581 * Approve / Reject the campaign page.
582 *
583 * @param int $id
584 * Campaign page id.
585 *
586 * @param bool $is_active
587 */
588 public static function setIsActive($id, $is_active) {
589 switch ($is_active) {
590 case 0:
591 $is_active = 3;
592 break;
593
594 case 1:
595 $is_active = 2;
596 break;
597 }
598
599 CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'status_id', $is_active);
600
601 $pcpTitle = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $id, 'title');
602 $pcpPageType = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $id, 'page_type');
603
604 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
605 $pcpStatus = $pcpStatus[$is_active];
606
607 CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", [
608 1 => $pcpTitle,
609 2 => $pcpStatus,
610 ]), 'Status Updated', 'success');
611
612 // send status change mail
613 $result = self::sendStatusUpdate($id, $is_active, FALSE, $pcpPageType);
614
615 if ($result) {
616 CRM_Core_Session::setStatus(ts("A notification email has been sent to the supporter."), ts('Email Sent'), 'success');
617 }
618 }
619
620 /**
621 * Send notification email to supporter.
622 *
623 * 1. when their PCP status is changed by site admin.
624 * 2. when supporter initially creates a Personal Campaign Page ($isInitial set to true).
625 *
626 * @param int $pcpId
627 * Campaign page id.
628 * @param int $newStatus
629 * Pcp status id.
630 * @param bool|int $isInitial is it the first time, campaign page has been created by the user
631 *
632 * @param string $component
633 *
634 * @throws Exception
635 * @return null
636 */
637 public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE, $component = 'contribute') {
638 $pcpStatusName = CRM_Core_OptionGroup::values("pcp_status", FALSE, FALSE, FALSE, NULL, 'name');
639 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
640 $config = CRM_Core_Config::singleton();
641
642 if (!isset($pcpStatus[$newStatus])) {
643 return FALSE;
644 }
645
646 require_once 'Mail/mime.php';
647
648 //set loginUrl
649 $loginURL = $config->userSystem->getLoginURL();
650
651 // used in subject templates
652 $contribPageTitle = self::getPcpPageTitle($pcpId, $component);
653
654 $tplParams = [
655 'loginUrl' => $loginURL,
656 'contribPageTitle' => $contribPageTitle,
657 'pcpId' => $pcpId,
658 ];
659
660 //get the default domain email address.
661 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
662
663 if (!$domainEmailAddress || $domainEmailAddress == 'info@EXAMPLE.ORG') {
664 $fixUrl = CRM_Utils_System::url('civicrm/admin/options/from_email_address', 'reset=1');
665 throw new CRM_Core_Exception(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', [1 => $fixUrl]));
666 }
667
668 $receiptFrom = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
669
670 // get recipient (supporter) name and email
671 $params = ['id' => $pcpId];
672 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
673 list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($pcpInfo['contact_id']);
674
675 // get pcp block info
676 list($blockId, $eid) = self::getPcpBlockEntityId($pcpId, $component);
677 $params = ['id' => $blockId];
678 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlockInfo);
679
680 // assign urls required in email template
681 if ($pcpStatusName[$newStatus] == 'Approved') {
682 $tplParams['isTellFriendEnabled'] = $pcpBlockInfo['is_tellfriend_enabled'];
683 if ($pcpBlockInfo['is_tellfriend_enabled']) {
684 $pcpTellFriendURL = CRM_Utils_System::url('civicrm/friend',
685 "reset=1&eid=$pcpId&blockId=$blockId&pcomponent=pcp",
686 TRUE, NULL, FALSE, TRUE
687 );
688 $tplParams['pcpTellFriendURL'] = $pcpTellFriendURL;
689 }
690 }
691 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
692 "reset=1&id=$pcpId",
693 TRUE, NULL, FALSE, TRUE
694 );
695 $tplParams['pcpInfoURL'] = $pcpInfoURL;
696 $tplParams['contribPageTitle'] = $contribPageTitle;
697 if ($emails = CRM_Utils_Array::value('notify_email', $pcpBlockInfo)) {
698 $emailArray = explode(',', $emails);
699 $tplParams['pcpNotifyEmailAddress'] = $emailArray[0];
700 }
701 // get appropriate message based on status
702 $tplParams['pcpStatus'] = $pcpStatus[$newStatus];
703
704 $tplName = $isInitial ? 'pcp_supporter_notify' : 'pcp_status_change';
705
706 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
707 [
708 'groupName' => 'msg_tpl_workflow_contribution',
709 'valueName' => $tplName,
710 'contactId' => $pcpInfo['contact_id'],
711 'tplParams' => $tplParams,
712 'from' => $receiptFrom,
713 'toName' => $name,
714 'toEmail' => $address,
715 ]
716 );
717 return $sent;
718 }
719
720 /**
721 * Enable / Disable the campaign page.
722 *
723 * @param int $id
724 * Campaign page id.
725 *
726 * @param bool $is_active
727 *
728 * @return bool
729 * true if we found and updated the object, else false
730 */
731 public static function setDisable($id, $is_active) {
732 return CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'is_active', $is_active);
733 }
734
735 /**
736 * Get pcp block is active.
737 *
738 * @param int $pcpId
739 * @param $component
740 *
741 * @return int
742 */
743 public static function getStatus($pcpId, $component) {
744 $query = "
745 SELECT pb.is_active
746 FROM civicrm_pcp pcp
747 LEFT JOIN civicrm_pcp_block pb ON ( pcp.page_id = pb.entity_id )
748 WHERE pcp.id = %1
749 AND pb.entity_table = %2";
750
751 $entity_table = self::getPcpEntityTable($component);
752
753 $params = [1 => [$pcpId, 'Integer'], 2 => [$entity_table, 'String']];
754 return CRM_Core_DAO::singleValueQuery($query, $params);
755 }
756
757 /**
758 * Get pcp block is enabled for component page.
759 *
760 * @param int $pageId
761 * @param $component
762 *
763 * @return string
764 */
765 public static function getPcpBlockStatus($pageId, $component) {
766 $query = "
767 SELECT pb.link_text as linkText
768 FROM civicrm_pcp_block pb
769 WHERE pb.is_active = 1 AND
770 pb.entity_id = %1 AND
771 pb.entity_table = %2";
772
773 $entity_table = self::getPcpEntityTable($component);
774
775 $params = [1 => [$pageId, 'Integer'], 2 => [$entity_table, 'String']];
776 return CRM_Core_DAO::singleValueQuery($query, $params);
777 }
778
779 /**
780 * Find out if the PCP block is in use by one or more PCP page.
781 *
782 * @param int $id
783 * Pcp block id.
784 *
785 * @return Bool
786 */
787 public static function getPcpBlockInUse($id) {
788 $query = "
789 SELECT count(*)
790 FROM civicrm_pcp pcp
791 WHERE pcp.pcp_block_id = %1";
792
793 $params = [1 => [$id, 'Integer']];
794 $result = CRM_Core_DAO::singleValueQuery($query, $params);
795 return $result > 0;
796 }
797
798 /**
799 * Get email is enabled for supporter's profile
800 *
801 * @param int $profileId
802 * Supporter's profile id.
803 *
804 * @return bool
805 */
806 public static function checkEmailProfile($profileId) {
807 $query = "
808 SELECT field_name
809 FROM civicrm_uf_field
810 WHERE field_name like 'email%' And is_active = 1 And uf_group_id = %1";
811
812 $params = [1 => [$profileId, 'Integer']];
813 $dao = CRM_Core_DAO::executeQuery($query, $params);
814 if (!$dao->fetch()) {
815 return TRUE;
816 }
817 return FALSE;
818 }
819
820 /**
821 * Obtain the title of page associated with a pcp.
822 *
823 * @param int $pcpId
824 * @param $component
825 *
826 * @return int
827 */
828 public static function getPcpPageTitle($pcpId, $component) {
829 if ($component == 'contribute') {
830 $query = "
831 SELECT cp.title
832 FROM civicrm_pcp pcp
833 LEFT JOIN civicrm_contribution_page as cp ON ( cp.id = pcp.page_id )
834 WHERE pcp.id = %1";
835 }
836 elseif ($component == 'event') {
837 $query = "
838 SELECT ce.title
839 FROM civicrm_pcp pcp
840 LEFT JOIN civicrm_event as ce ON ( ce.id = pcp.page_id )
841 WHERE pcp.id = %1";
842 }
843
844 $params = [1 => [$pcpId, 'Integer']];
845 return CRM_Core_DAO::singleValueQuery($query, $params);
846 }
847
848 /**
849 * Get pcp block & entity id given pcp id
850 *
851 * @param int $pcpId
852 * @param $component
853 *
854 * @return string
855 */
856 public static function getPcpBlockEntityId($pcpId, $component) {
857 $entity_table = self::getPcpEntityTable($component);
858
859 $query = "
860 SELECT pb.id as pcpBlockId, pb.entity_id
861 FROM civicrm_pcp pcp
862 LEFT JOIN civicrm_pcp_block pb ON ( pb.entity_id = pcp.page_id AND pb.entity_table = %2 )
863 WHERE pcp.id = %1";
864
865 $params = [1 => [$pcpId, 'Integer'], 2 => [$entity_table, 'String']];
866 $dao = CRM_Core_DAO::executeQuery($query, $params);
867 if ($dao->fetch()) {
868 return [$dao->pcpBlockId, $dao->entity_id];
869 }
870
871 return [];
872 }
873
874 /**
875 * Get pcp entity table given a component.
876 *
877 * @param $component
878 *
879 * @return string
880 */
881 public static function getPcpEntityTable($component) {
882 $entity_table_map = [
883 'event' => 'civicrm_event',
884 'civicrm_event' => 'civicrm_event',
885 'contribute' => 'civicrm_contribution_page',
886 'civicrm_contribution_page' => 'civicrm_contribution_page',
887 ];
888 return $entity_table_map[$component] ?? FALSE;
889 }
890
891 /**
892 * Get supporter profile id.
893 *
894 * @param int $component_id
895 * @param string $component
896 *
897 * @return int
898 */
899 public static function getSupporterProfileId($component_id, $component = 'contribute') {
900 $entity_table = self::getPcpEntityTable($component);
901
902 $query = "
903 SELECT pcp.supporter_profile_id
904 FROM civicrm_pcp_block pcp
905 INNER JOIN civicrm_uf_group ufgroup
906 ON pcp.supporter_profile_id = ufgroup.id
907 WHERE pcp.entity_id = %1
908 AND pcp.entity_table = %2
909 AND ufgroup.is_active = 1";
910
911 $params = [1 => [$component_id, 'Integer'], 2 => [$entity_table, 'String']];
912 if (!$supporterProfileId = CRM_Core_DAO::singleValueQuery($query, $params)) {
913 throw new CRM_Core_Exception(ts('Supporter profile is not set for this Personal Campaign Page or the profile is disabled. Please contact the site administrator if you need assistance.'));
914 }
915 else {
916 return $supporterProfileId;
917 }
918 }
919
920 /**
921 * Get owner notification id.
922 *
923 * @param int $component_id
924 * @param $component
925 *
926 * @return int
927 */
928 public static function getOwnerNotificationId($component_id, $component = 'contribute') {
929 $entity_table = self::getPcpEntityTable($component);
930 $query = "
931 SELECT pb.owner_notify_id
932 FROM civicrm_pcp_block pb
933 WHERE pb.entity_id = %1 AND pb.entity_table = %2";
934 $params = [1 => [$component_id, 'Integer'], 2 => [$entity_table, 'String']];
935 if (!$ownerNotificationId = CRM_Core_DAO::singleValueQuery($query, $params)) {
936 throw new CRM_Core_Exception(ts('Owner Notification is not set for this Personal Campaign Page. Please contact the site administrator if you need assistance.'));
937 }
938 else {
939 return $ownerNotificationId;
940 }
941 }
942
943 /**
944 * Get the title of the pcp.
945 *
946 * @param string $component
947 * @param int $id
948 *
949 * @return bool|string|null
950 */
951 protected static function getPcpTitle(string $component, int $id) {
952 if ($component === 'contribute') {
953 return CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_page_id', $id);
954 }
955 return CRM_Core_PseudoConstant::getLabel('CRM_Event_BAO_Participant', 'event_id', $id);
956 }
957
958 }