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