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