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