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