Merge pull request #4979 from xurizaemon/codingstandards-12
[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 +--------------------------------------------------------------------+
26*/
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 /**
38 * The action links that we need to display for the browse screen
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 /**
100fef9d 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 /**
100fef9d 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 /**
100fef9d 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;
216 $pageTitle = CRM_Utils_Array::value($pcpBlockDao->target_entity_id, $$component);
6a488035
TO
217 $pcpBlock[] = array(
218 'pageId' => $pcpBlockDao->target_entity_id,
219 'pageTitle' => $pageTitle,
2a15a371 220 'component' => $pcpBlockDao->target_entity_type,
6a488035
TO
221 'action' => $action,
222 );
223 }
224
225 return array($pcpBlock, $pcpInfo);
226 }
227
228 /**
100fef9d 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 /**
280 * Get action links
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'),
6a488035
TO
292 'url' => 'civicrm/contribute/campaign',
293 'qs' => 'action=add&reset=1&pageId=%%pageId%%&component=%%pageComponent%%',
294 'title' => ts('Configure'),
295 ),
296 );
297
298 self::$_pcpLinks['all'] = array(
9d9922e7 299 CRM_Core_Action::UPDATE => array(
300 'name' => ts('Edit Your Page'),
6a488035
TO
301 'url' => 'civicrm/pcp/info',
302 'qs' => 'action=update&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
303 'title' => ts('Configure'),
304 ),
9d9922e7 305 CRM_Core_Action::DETACH => array(
306 'name' => ts('Tell Friends'),
6a488035
TO
307 'url' => 'civicrm/friend',
308 'qs' => 'eid=%%pcpId%%&blockId=%%pcpBlock%%&reset=1&pcomponent=pcp&component=%%pageComponent%%',
309 'title' => ts('Tell Friends'),
310 ),
ff06e012
DG
311 CRM_Core_Action::VIEW => array(
312 'name' => ts('URL for this Page'),
313 'url' => 'civicrm/pcp/info',
314 'qs' => 'reset=1&id=%%pcpId%%&component=%%pageComponent%%',
315 'title' => ts('URL for this Page'),
316 ),
9d9922e7 317 CRM_Core_Action::BROWSE => array(
318 'name' => ts('Update Contact Information'),
6a488035
TO
319 'url' => 'civicrm/pcp/info',
320 'qs' => 'action=browse&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
321 'title' => ts('Update Contact Information'),
322 ),
9d9922e7 323 CRM_Core_Action::ENABLE => array(
324 'name' => ts('Enable'),
6a488035
TO
325 'url' => 'civicrm/pcp',
326 'qs' => 'action=enable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
327 'title' => ts('Enable'),
328 ),
9d9922e7 329 CRM_Core_Action::DISABLE => array(
330 'name' => ts('Disable'),
6a488035
TO
331 'url' => 'civicrm/pcp',
332 'qs' => 'action=disable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
333 'title' => ts('Disable'),
334 ),
9d9922e7 335 CRM_Core_Action::DELETE => array(
336 'name' => ts('Delete'),
6a488035
TO
337 'url' => 'civicrm/pcp',
338 'qs' => 'action=delete&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
339 'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
340 'title' => ts('Delete'),
341 ),
342 );
343 }
344 return self::$_pcpLinks;
345 }
346
347 /**
100fef9d 348 * Delete the campaign page
6a488035 349 *
db95eff6
TO
350 * @param int $id
351 * Campaign page id.
6a488035 352 *
d5cc0fc2 353 * @return;
6a488035
TO
354 */
355 public static function deleteById($id) {
356 CRM_Utils_Hook::pre('delete', 'Campaign', $id, CRM_Core_DAO::$_nullArray);
357
358 $transaction = new CRM_Core_Transaction();
359
360 // delete from pcp table
361 $pcp = new CRM_PCP_DAO_PCP();
362 $pcp->id = $id;
363 $pcp->delete();
364
365 $transaction->commit();
366
367 CRM_Utils_Hook::post('delete', 'Campaign', $id, $pcp);
368 }
369
370 /**
c490a46a 371 * Build the form object
6a488035 372 *
db95eff6
TO
373 * @param CRM_Core_Form $form
374 * Form object.
6a488035 375 *
355ba699 376 * @return void
6a488035 377 */
cad004cf 378 public static function buildPCPForm($form) {
6a488035
TO
379 $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"));
380
381 $form->addElement('checkbox', 'is_approval_needed', ts('Approval required'));
382
9d9922e7 383 $profile = array();
6a488035 384 $isUserRequired = NULL;
9d9922e7 385 $config = CRM_Core_Config::singleton();
6a488035
TO
386 if ($config->userFramework != 'Standalone') {
387 $isUserRequired = 2;
388 }
9d9922e7 389 CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, array(
390 'title',
21dfd5f5 391 'is_active',
9d9922e7 392 ));
6a488035
TO
393 if (!empty($profiles)) {
394 foreach ($profiles as $key => $value) {
395 if ($value['is_active']) {
396 $profile[$key] = $value['title'];
397 }
398 }
399 $form->assign('profile', $profile);
400 }
401
a33733e6 402 $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), array('' => ts('- select -')) + $profile, TRUE);
6a488035
TO
403
404 $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);"));
405
406 $form->add('text',
407 'tellfriend_limit',
408 ts("'Tell a friend' maximum recipients limit"),
409 CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'tellfriend_limit')
410 );
411 $form->addRule('tellfriend_limit', ts('Please enter a valid limit.'), 'integer');
412
413 $form->add('text',
414 'link_text',
415 ts("'Create Personal Campaign Page' link text"),
416 CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'link_text')
417 );
418
419 $form->add('text', 'notify_email', ts('Notify Email'), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'notify_email'));
420 }
421
422
e0ef6999 423 /**
d424ffde
CW
424 * Add PCP form elements to a form
425 *
db95eff6 426 * @param int $pcpId
d75f2f47 427 * @param CRM_Core_Page $page
e0ef6999
EM
428 * @param null $elements
429 */
00be9182 430 public function buildPcp($pcpId, &$page, &$elements = NULL) {
6a488035
TO
431
432 $prms = array('id' => $pcpId);
433 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
6a488035
TO
434 if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($pcpId)) {
435 if ($pcpInfo['page_type'] == 'event') {
eea141c0
DG
436 $pcp_supporter_text = ts('This event registration is being made thanks to effort of <strong>%1</strong>, who supports our campaign. ', array(1 => $pcpSupporter));
437 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'event');
22e263ad 438 if (!empty($text)) {
eea141c0
DG
439 $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!";
440 }
6a488035
TO
441 }
442 else {
eea141c0
DG
443 $pcp_supporter_text = ts('This contribution 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'], 'contribute');
22e263ad 445 if (!empty($text)) {
eea141c0
DG
446 $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!";
447 }
6a488035 448 }
77b97be7 449
eea141c0 450 $page->assign('pcpSupporterText', $pcp_supporter_text);
6a488035
TO
451 }
452 $page->assign('pcp', TRUE);
453
454 // build honor roll fields for registration form if supporter has honor roll enabled for their PCP
455 if ($pcpInfo['is_honor_roll']) {
456 $page->assign('is_honor_roll', TRUE);
457 $page->add('checkbox', 'pcp_display_in_roll', ts('Show my support in the public honor roll'), NULL, NULL,
458 array('onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );")
459 );
460 $extraOption = array('onclick' => "return pcpAnonymous( );");
9d9922e7 461 $elements = array();
353ffa53
TO
462 $elements[] = &$page->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
463 $elements[] = &$page->createElement('radio', NULL, '', ts('List my support anonymously'), 1, $extraOption);
6a488035
TO
464 $page->addGroup($elements, 'pcp_is_anonymous', NULL, '&nbsp;&nbsp;&nbsp;');
465 $page->_defaults['pcp_is_anonymous'] = 0;
466
467 $page->add('text', 'pcp_roll_nickname', ts('Name'), array('maxlength' => 30));
468 $page->add('textarea', "pcp_personal_note", ts('Personal Note'), array('style' => 'height: 3em; width: 40em;'));
469 }
470 else {
471 $page->assign('is_honor_roll', FALSE);
472 }
473 }
474
e0ef6999 475 /**
d424ffde
CW
476 * Process a PCP contribution
477 *
100fef9d 478 * @param int $pcpId
e0ef6999
EM
479 * @param $component
480 * @param $entity
481 *
482 * @return array
483 */
9d9922e7 484 public static function handlePcp($pcpId, $component, $entity) {
6a488035 485
9d9922e7 486 self::getPcpEntityTable($component);
6a488035
TO
487
488 if (!$pcpId) {
489 return FALSE;
490 }
491
492 $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
493
2158332a 494 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
6a488035
TO
495
496 $params = array('id' => $pcpId);
497 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
498
499 $params = array('id' => $pcpInfo['pcp_block_id']);
500 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlock);
501
502 $params = array('id' => $pcpInfo['page_id']);
9d9922e7 503 $now = time();
6a488035
TO
504
505 if ($component == 'event') {
506 // figure out where to redirect if an exception occurs below based on target entity
507 $urlBase = 'civicrm/event/register';
508
509 // ignore startDate for events - PCP's can be active long before event start date
510 $startDate = 0;
9d9922e7 511 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity));
6a488035 512 }
6a488035
TO
513 elseif ($component == 'contribute') {
514 $urlBase = 'civicrm/contribute/transact';
515 //start and end date of the contribution page
516 $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('start_date', $entity));
9d9922e7 517 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity));
6a488035
TO
518 }
519
520 // define redirect url back to contrib page or event if needed
481a74f4 521 $url = CRM_Utils_System::url($urlBase, "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE);
6a488035
TO
522
523 if ($pcpBlock['target_entity_id'] != $entity['id']) {
524 $statusMessage = ts('This page is not related to the Personal Campaign Page you have just visited. However you can still make a contribution here.');
525 CRM_Core_Error::statusBounce($statusMessage, $url);
526 }
527 elseif ($pcpInfo['status_id'] != $approvedId) {
528 $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']]));
529 CRM_Core_Error::statusBounce($statusMessage, $url);
530 }
a7488080 531 elseif (empty($pcpBlock['is_active'])) {
6a488035
TO
532 $statusMessage = ts('Personal Campaign Pages are currently not enabled for this contribution page. However you can still support the campaign here.');
533 CRM_Core_Error::statusBounce($statusMessage, $url);
534 }
a7488080 535 elseif (empty($pcpInfo['is_active'])) {
6a488035
TO
536 $statusMessage = ts('The Personal Campaign Page you have just visited is currently inactive. However you can still support the campaign here.');
537 CRM_Core_Error::statusBounce($statusMessage, $url);
538 }
539 // Check if we're in range for contribution page start and end dates. for events, check if after event end date
540 elseif (($startDate && $startDate > $now) || ($endDate && $endDate < $now)) {
541 $customStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $entity));
542 $customEndDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $entity));
543 if ($startDate && $endDate) {
544 $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.',
545 array(1 => $customStartDate, 2 => $customEndDate)
546 );
547 CRM_Core_Error::statusBounce($statusMessage, $url);
548 }
549 elseif ($startDate) {
550 $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));
551 CRM_Core_Error::statusBounce($statusMessage, $url);
552 }
553 elseif ($endDate) {
554 if ($component == 'event') {
555 // Target_entity is an event and the event is over, redirect to event info instead of event registration page.
556 $url = CRM_Utils_System::url('civicrm/event/info',
557 "reset=1&id={$pcpBlock['entity_id']}",
558 FALSE, NULL, FALSE, TRUE
559 );
560 $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', array(1 => $customEndDate));
561 CRM_Core_Error::statusBounce($statusMessage, $url);
9d9922e7 562 }
563 else {
6a488035
TO
564 $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));
565 CRM_Core_Error::statusBounce($statusMessage, $url);
566 }
567 }
568 }
569
570 return array(
571 'pcpId' => $pcpId,
572 'pcpBlock' => $pcpBlock,
573 'pcpInfo' => $pcpInfo,
574 );
575 }
576
577 /**
100fef9d 578 * Approve / Reject the campaign page
6a488035 579 *
db95eff6
TO
580 * @param int $id
581 * Campaign page id.
6a488035 582 *
77b97be7
EM
583 * @param $is_active
584 *
d5cc0fc2 585 * @return;
6a488035 586 */
00be9182 587 public static function setIsActive($id, $is_active) {
6a488035
TO
588 switch ($is_active) {
589 case 0:
590 $is_active = 3;
591 break;
592
593 case 1:
594 $is_active = 2;
595 break;
596 }
597
598 CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'status_id', $is_active);
599
9d9922e7 600 $pcpTitle = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $id, 'title');
601 $pcpPageType = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $id, 'page_type');
6a488035 602
2158332a 603 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
6a488035
TO
604 $pcpStatus = $pcpStatus[$is_active];
605
9d9922e7 606 CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", array(
607 1 => $pcpTitle,
21dfd5f5 608 2 => $pcpStatus,
9d9922e7 609 )), 'Status Updated', 'success');
6a488035
TO
610
611 // send status change mail
612 $result = self::sendStatusUpdate($id, $is_active, FALSE, $pcpPageType);
613
614 if ($result) {
615 CRM_Core_Session::setStatus(ts("A notification email has been sent to the supporter."), ts('Email Sent'), 'success');
616 }
617 }
618
619 /**
100fef9d 620 * Send notfication email to supporter
6a488035
TO
621 * 1. when their PCP status is changed by site admin.
622 * 2. when supporter initially creates a Personal Campaign Page ($isInitial set to true).
623 *
db95eff6
TO
624 * @param int $pcpId
625 * Campaign page id.
626 * @param int $newStatus
627 * Pcp status id.
2a6da8d7 628 * @param bool|int $isInitial is it the first time, campaign page has been created by the user
6a488035 629 *
2a6da8d7
EM
630 * @param string $component
631 *
632 * @throws Exception
6a488035 633 * @return null
6a488035 634 */
00be9182 635 public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE, $component = 'contribute') {
aef123f6
C
636 $pcpStatusName = CRM_Core_OptionGroup::values("pcp_status", FALSE, FALSE, FALSE, NULL, 'name');
637 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
6a488035
TO
638 $config = CRM_Core_Config::singleton();
639
640 if (!isset($pcpStatus[$newStatus])) {
641 return FALSE;
642 }
643
644 require_once 'Mail/mime.php';
645
646 //set loginUrl
647 $loginURL = $config->userSystem->getLoginURL();
648
649 // used in subject templates
650 $contribPageTitle = self::getPcpPageTitle($pcpId, $component);
651
652 $tplParams = array(
653 'loginUrl' => $loginURL,
654 'contribPageTitle' => $contribPageTitle,
655 'pcpId' => $pcpId,
656 );
657
658 //get the default domain email address.
659 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
660
661 if (!$domainEmailAddress || $domainEmailAddress == 'info@EXAMPLE.ORG') {
662 $fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1');
663 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)));
664 }
665
666 $receiptFrom = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
667
668 // get recipient (supporter) name and email
669 $params = array('id' => $pcpId);
670 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
671 list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($pcpInfo['contact_id']);
672
673 // get pcp block info
674 list($blockId, $eid) = self::getPcpBlockEntityId($pcpId, $component);
675 $params = array('id' => $blockId);
676 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlockInfo);
677
678 // assign urls required in email template
aef123f6 679 if ($pcpStatusName[$newStatus] == 'Approved') {
6a488035
TO
680 $tplParams['isTellFriendEnabled'] = $pcpBlockInfo['is_tellfriend_enabled'];
681 if ($pcpBlockInfo['is_tellfriend_enabled']) {
682 $pcpTellFriendURL = CRM_Utils_System::url('civicrm/friend',
683 "reset=1&eid=$pcpId&blockId=$blockId&pcomponent=pcp",
684 TRUE, NULL, FALSE, TRUE
685 );
686 $tplParams['pcpTellFriendURL'] = $pcpTellFriendURL;
687 }
688 }
689 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
690 "reset=1&id=$pcpId",
691 TRUE, NULL, FALSE, TRUE
692 );
693 $tplParams['pcpInfoURL'] = $pcpInfoURL;
694 $tplParams['contribPageTitle'] = $contribPageTitle;
695 if ($emails = CRM_Utils_Array::value('notify_email', $pcpBlockInfo)) {
696 $emailArray = explode(',', $emails);
697 $tplParams['pcpNotifyEmailAddress'] = $emailArray[0];
698 }
699 // get appropriate message based on status
700 $tplParams['pcpStatus'] = $pcpStatus[$newStatus];
701
702 $tplName = $isInitial ? 'pcp_supporter_notify' : 'pcp_status_change';
703
c6327d7d 704 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
705 array(
706 'groupName' => 'msg_tpl_workflow_contribution',
707 'valueName' => $tplName,
708 'contactId' => $pcpInfo['contact_id'],
709 'tplParams' => $tplParams,
710 'from' => $receiptFrom,
711 'toName' => $name,
712 'toEmail' => $address,
713 )
714 );
715 return $sent;
716 }
717
718 /**
100fef9d 719 * Enable / Disable the campaign page
6a488035 720 *
db95eff6
TO
721 * @param int $id
722 * Campaign page id.
6a488035 723 *
2a6da8d7 724 * @param $is_active
6a488035 725 * @return null
6a488035 726 */
00be9182 727 public static function setDisable($id, $is_active) {
6a488035
TO
728 return CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'is_active', $is_active);
729 }
730
731 /**
100fef9d 732 * Get pcp block is active
6a488035 733 *
c490a46a 734 * @param int $pcpId
2a6da8d7 735 * @param $component
6a488035
TO
736 *
737 * @return int
6a488035 738 */
00be9182 739 public static function getStatus($pcpId, $component) {
6a488035
TO
740 $query = "
741 SELECT pb.is_active
742 FROM civicrm_pcp pcp
743 LEFT JOIN civicrm_pcp_block pb ON ( pcp.page_id = pb.entity_id )
744 WHERE pcp.id = %1
745 AND pb.entity_table = %2";
746
747 $entity_table = self::getPcpEntityTable($component);
748
749 $params = array(1 => array($pcpId, 'Integer'), 2 => array($entity_table, 'String'));
750 return CRM_Core_DAO::singleValueQuery($query, $params);
751 }
752
753 /**
100fef9d 754 * Get pcp block is enabled for component page
6a488035 755 *
c490a46a 756 * @param int $pageId
2a6da8d7 757 * @param $component
6a488035 758 *
c490a46a 759 * @return string
6a488035 760 */
00be9182 761 public static function getPcpBlockStatus($pageId, $component) {
6a488035
TO
762 $query = "
763 SELECT pb.link_text as linkText
eea141c0
DG
764 FROM civicrm_pcp_block pb
765 WHERE pb.is_active = 1 AND
766 pb.entity_id = %1 AND
767 pb.entity_table = %2";
6a488035
TO
768
769 $entity_table = self::getPcpEntityTable($component);
770
771 $params = array(1 => array($pageId, 'Integer'), 2 => array($entity_table, 'String'));
772 return CRM_Core_DAO::singleValueQuery($query, $params);
773 }
774
775 /**
100fef9d 776 * Find out if the PCP block is in use by one or more PCP page
6a488035 777 *
db95eff6
TO
778 * @param int $id
779 * Pcp block id.
6a488035 780 *
d5cc0fc2 781 * @return Bool
6a488035 782 */
00be9182 783 public static function getPcpBlockInUse($id) {
6a488035
TO
784 $query = "
785 SELECT count(*)
786 FROM civicrm_pcp pcp
787 WHERE pcp.pcp_block_id = %1";
788
789 $params = array(1 => array($id, 'Integer'));
790 $result = CRM_Core_DAO::singleValueQuery($query, $params);
791 return $result > 0;
792 }
793
794 /**
100fef9d 795 * Get email is enabled for supporter's profile
6a488035 796 *
db95eff6
TO
797 * @param int $profileId
798 * Supporter's profile id.
6a488035 799 *
d5cc0fc2 800 * @return bool
6a488035 801 */
00be9182 802 public static function checkEmailProfile($profileId) {
6a488035
TO
803 $query = "
804SELECT field_name
805FROM civicrm_uf_field
806WHERE field_name like 'email%' And is_active = 1 And uf_group_id = %1";
807
808 $params = array(1 => array($profileId, 'Integer'));
809 $dao = CRM_Core_DAO::executeQuery($query, $params);
810 if (!$dao->fetch()) {
811 return TRUE;
812 }
813 return FALSE;
814 }
815
816 /**
100fef9d 817 * Obtain the title of page associated with a pcp
6a488035 818 *
c490a46a 819 * @param int $pcpId
dd244018
EM
820 * @param $component
821 *
6a488035 822 * @return int
6a488035 823 */
00be9182 824 public static function getPcpPageTitle($pcpId, $component) {
6a488035
TO
825 if ($component == 'contribute') {
826 $query = "
827 SELECT cp.title
828 FROM civicrm_pcp pcp
829 LEFT JOIN civicrm_contribution_page as cp ON ( cp.id = pcp.page_id )
830 WHERE pcp.id = %1";
831 }
832 elseif ($component == 'event') {
833 $query = "
834 SELECT ce.title
835 FROM civicrm_pcp pcp
836 LEFT JOIN civicrm_event as ce ON ( ce.id = pcp.page_id )
837 WHERE pcp.id = %1";
838 }
839
840 $params = array(1 => array($pcpId, 'Integer'));
841 return CRM_Core_DAO::singleValueQuery($query, $params);
842 }
843
844 /**
100fef9d 845 * Get pcp block & entity id given pcp id
6a488035 846 *
c490a46a 847 * @param int $pcpId
dd244018
EM
848 * @param $component
849 *
d5cc0fc2 850 * @return string
6a488035 851 */
00be9182 852 public static function getPcpBlockEntityId($pcpId, $component) {
6a488035
TO
853 $entity_table = self::getPcpEntityTable($component);
854
855 $query = "
856SELECT pb.id as pcpBlockId, pb.entity_id
857FROM civicrm_pcp pcp
858LEFT JOIN civicrm_pcp_block pb ON ( pb.entity_id = pcp.page_id AND pb.entity_table = %2 )
859WHERE pcp.id = %1";
860
861 $params = array(1 => array($pcpId, 'Integer'), 2 => array($entity_table, 'String'));
862 $dao = CRM_Core_DAO::executeQuery($query, $params);
863 if ($dao->fetch()) {
864 return array($dao->pcpBlockId, $dao->entity_id);
865 }
866
867 return array();
868 }
869
870 /**
100fef9d 871 * Get pcp entity table given a component.
6a488035 872 *
2a6da8d7
EM
873 * @param $component
874 *
d5cc0fc2 875 * @return string
6a488035 876 */
00be9182 877 public static function getPcpEntityTable($component) {
6a488035
TO
878 $entity_table_map = array(
879 'event' => 'civicrm_event',
880 'civicrm_event' => 'civicrm_event',
881 'contribute' => 'civicrm_contribution_page',
882 'civicrm_contribution_page' => 'civicrm_contribution_page',
883 );
884 return isset($entity_table_map[$component]) ? $entity_table_map[$component] : FALSE;
885 }
886
887 /**
100fef9d 888 * Get supporter profile id
6a488035 889 *
c490a46a 890 * @param int $component_id
fd31fa4c
EM
891 * @param string $component
892 *
6a488035 893 * @return int
6a488035 894 */
c1204160 895 public static function getSupporterProfileId($component_id, $component = 'contribute') {
6a488035
TO
896 $entity_table = self::getPcpEntityTable($component);
897
898 $query = "
899SELECT pcp.supporter_profile_id
900FROM civicrm_pcp_block pcp
901INNER JOIN civicrm_uf_group ufgroup
902 ON pcp.supporter_profile_id = ufgroup.id
903 WHERE pcp.entity_id = %1
904 AND pcp.entity_table = %2
905 AND ufgroup.is_active = 1";
906
907 $params = array(1 => array($component_id, 'Integer'), 2 => array($entity_table, 'String'));
908 if (!$supporterProfileId = CRM_Core_DAO::singleValueQuery($query, $params)) {
909 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.'));
910 }
911 else {
912 return $supporterProfileId;
913 }
914 }
915}