commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-old / civicrm / CRM / PCP / BAO / PCP.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class CRM_PCP_BAO_PCP extends CRM_PCP_DAO_PCP {
36
37 /**
38 * The action links that we need to display for the browse screen.
39 *
40 * @var array
41 */
42 static $_pcpLinks = NULL;
43
44 /**
45 */
46 public function __construct() {
47 parent::__construct();
48 }
49
50 /**
51 * Add or update either a Personal Campaign Page OR a PCP Block.
52 *
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.
57 *
58 *
59 * @return object
60 */
61 public static function add(&$params, $pcpBlock = TRUE) {
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)) {
81 $config = &CRM_Core_Config::singleton();
82 $dao->currency = $config->defaultCurrency;
83 }
84
85 $dao->save();
86 return $dao;
87 }
88
89 /**
90 * Get the Display name of a contact for a PCP.
91 *
92 * @param int $id
93 * Id for the PCP.
94 *
95 * @return null|string
96 * Dispaly name of the contact if found
97 */
98 public static function displayName($id) {
99 $id = CRM_Utils_Type::escape($id, 'Integer');
100
101 $query = "
102 SELECT civicrm_contact.display_name
103 FROM civicrm_pcp, civicrm_contact
104 WHERE 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 /**
111 * Return PCP Block info for dashboard.
112 *
113 * @param int $contactId
114 *
115 * @return array
116 * array of Pcp if found
117 */
118 public static function getPcpDashboardInfo($contactId) {
119 $links = self::pcpLinks();
120
121 $query = "
122 SELECT * FROM civicrm_pcp pcp
123 WHERE pcp.is_active = 1
124 AND pcp.contact_id = %1
125 ORDER BY page_type, page_id";
126
127 $params = array(1 => array($contactId, 'Integer'));
128
129 $pcpInfoDao = CRM_Core_DAO::executeQuery($query, $params);
130 $pcpInfo = array();
131 $hide = $mask = array_sum(array_keys($links['all']));
132 $contactPCPPages = array();
133
134 $event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
135 $contribute = CRM_Contribute_PseudoConstant::contributionPage();
136 $pcpStatus = CRM_Contribute_PseudoConstant::pcpStatus();
137 $approved = CRM_Utils_Array::key('Approved', $pcpStatus);
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 }
165 $action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'),
166 FALSE, 'pcp.dashboard.active', 'PCP', $pcpInfoDao->id);
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}'
186 AND target_entity_id NOT IN ( " . implode(',', $entityIds) . ") )";
187 }
188
189 $clause = ' AND ' . implode(' OR ', $excludePageClause);
190 }
191
192 $query = "
193 SELECT *
194 FROM civicrm_pcp_block block
195 LEFT JOIN civicrm_pcp pcp ON pcp.pcp_block_id = block.id
196 WHERE block.is_active = 1
197 {$clause}
198 GROUP BY block.id
199 ORDER BY target_entity_type, target_entity_id
200 ";
201 $pcpBlockDao = CRM_Core_DAO::executeQuery($query);
202 $pcpBlock = array();
203 $mask = 0;
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 }
212 $pcpLink = $links['add'];
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);
215 $component = $pcpBlockDao->target_entity_type;
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 }
223 }
224
225 return array($pcpBlock, $pcpInfo);
226 }
227
228 /**
229 * Show the total amount for Personal Campaign Page on thermometer.
230 *
231 * @param array $pcpId
232 * Contains the pcp ID.
233 *
234 *
235 * @return total
236 * amount
237 */
238 public static function thermoMeter($pcpId) {
239 $query = "
240 SELECT SUM(cc.total_amount) as total
241 FROM civicrm_pcp pcp
242 LEFT JOIN civicrm_contribution_soft cs ON ( pcp.id = cs.pcp_id )
243 LEFT JOIN civicrm_contribution cc ON ( cs.contribution_id = cc.id)
244 WHERE 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 /**
251 * Show the amount, nickname on honor roll
252 *
253 * @param array $pcpId
254 * Contains the pcp ID.
255 *
256 *
257 * @return array
258 */
259 public static function honorRoll($pcpId) {
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 *
282 * @return array
283 * (reference) of action links
284 */
285 public static function &pcpLinks() {
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(
290 CRM_Core_Action::ADD => array(
291 'name' => ts('Create a Personal Campaign Page'),
292 'class' => 'no-popup',
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(
300 CRM_Core_Action::UPDATE => array(
301 'name' => ts('Edit Your Page'),
302 'url' => 'civicrm/pcp/info',
303 'qs' => 'action=update&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
304 'title' => ts('Configure'),
305 ),
306 CRM_Core_Action::DETACH => array(
307 'name' => ts('Tell Friends'),
308 'url' => 'civicrm/friend',
309 'qs' => 'eid=%%pcpId%%&blockId=%%pcpBlock%%&reset=1&pcomponent=pcp&component=%%pageComponent%%',
310 'title' => ts('Tell Friends'),
311 ),
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 ),
318 CRM_Core_Action::BROWSE => array(
319 'name' => ts('Update Contact Information'),
320 'url' => 'civicrm/pcp/info',
321 'qs' => 'action=browse&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
322 'title' => ts('Update Contact Information'),
323 ),
324 CRM_Core_Action::ENABLE => array(
325 'name' => ts('Enable'),
326 'url' => 'civicrm/pcp',
327 'qs' => 'action=enable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
328 'title' => ts('Enable'),
329 ),
330 CRM_Core_Action::DISABLE => array(
331 'name' => ts('Disable'),
332 'url' => 'civicrm/pcp',
333 'qs' => 'action=disable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
334 'title' => ts('Disable'),
335 ),
336 CRM_Core_Action::DELETE => array(
337 'name' => ts('Delete'),
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 /**
349 * Delete the campaign page.
350 *
351 * @param int $id
352 * Campaign page id.
353 *
354 * @return;
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 /**
372 * Build the form object.
373 *
374 * @param CRM_Core_Form $form
375 * Form object.
376 *
377 * @return void
378 */
379 public static function buildPCPForm($form) {
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
384 $profile = array();
385 $isUserRequired = NULL;
386 $config = CRM_Core_Config::singleton();
387 if ($config->userFramework != 'Standalone') {
388 $isUserRequired = 2;
389 }
390 CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, array(
391 'title',
392 'is_active',
393 ));
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
403 $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), array('' => ts('- select -')) + $profile, TRUE);
404
405 //CRM-15821 - To add new option for PCP "Owner" notification
406 $ownerNotifications = CRM_Core_OptionGroup::values('pcp_owner_notify');
407 $form->addRadio('owner_notify_id', ts('Owner Email Notification'), $ownerNotifications, NULL, '<br/>', TRUE);
408
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
428 /**
429 * Add PCP form elements to a form.
430 *
431 * @param int $pcpId
432 * @param CRM_Core_Page $page
433 * @param null $elements
434 */
435 public static function buildPcp($pcpId, &$page, &$elements = NULL) {
436
437 $prms = array('id' => $pcpId);
438 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
439 if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($pcpId)) {
440 if ($pcpInfo['page_type'] == 'event') {
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));
442 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'event');
443 if (!empty($text)) {
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 }
446 }
447 else {
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));
449 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'contribute');
450 if (!empty($text)) {
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 }
453 }
454
455 $page->assign('pcpSupporterText', $pcp_supporter_text);
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( );");
466 $elements = array();
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);
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
480 /**
481 * Process a PCP contribution.
482 *
483 * @param int $pcpId
484 * @param $component
485 * @param $entity
486 *
487 * @return array
488 */
489 public static function handlePcp($pcpId, $component, $entity) {
490
491 self::getPcpEntityTable($component);
492
493 if (!$pcpId) {
494 return FALSE;
495 }
496
497 $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
498
499 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
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']);
508 $now = time();
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;
516 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity));
517 }
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));
522 $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity));
523 }
524
525 // define redirect url back to contrib page or event if needed
526 $url = CRM_Utils_System::url($urlBase, "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE);
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 }
536 elseif (empty($pcpBlock['is_active'])) {
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 }
540 elseif (empty($pcpInfo['is_active'])) {
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);
567 }
568 else {
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 /**
583 * Approve / Reject the campaign page
584 *
585 * @param int $id
586 * Campaign page id.
587 *
588 * @param $is_active
589 *
590 * @return;
591 */
592 public static function setIsActive($id, $is_active) {
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
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');
607
608 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
609 $pcpStatus = $pcpStatus[$is_active];
610
611 CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", array(
612 1 => $pcpTitle,
613 2 => $pcpStatus,
614 )), 'Status Updated', 'success');
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 /**
625 * Send notfication email to supporter
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 *
629 * @param int $pcpId
630 * Campaign page id.
631 * @param int $newStatus
632 * Pcp status id.
633 * @param bool|int $isInitial is it the first time, campaign page has been created by the user
634 *
635 * @param string $component
636 *
637 * @throws Exception
638 * @return null
639 */
640 public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE, $component = 'contribute') {
641 $pcpStatusName = CRM_Core_OptionGroup::values("pcp_status", FALSE, FALSE, FALSE, NULL, 'name');
642 $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
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
684 if ($pcpStatusName[$newStatus] == 'Approved') {
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
709 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
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 /**
724 * Enable / Disable the campaign page
725 *
726 * @param int $id
727 * Campaign page id.
728 *
729 * @param $is_active
730 * @return null
731 */
732 public static function setDisable($id, $is_active) {
733 return CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'is_active', $is_active);
734 }
735
736 /**
737 * Get pcp block is active.
738 *
739 * @param int $pcpId
740 * @param $component
741 *
742 * @return int
743 */
744 public static function getStatus($pcpId, $component) {
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 /**
759 * Get pcp block is enabled for component page.
760 *
761 * @param int $pageId
762 * @param $component
763 *
764 * @return string
765 */
766 public static function getPcpBlockStatus($pageId, $component) {
767 $query = "
768 SELECT pb.link_text as linkText
769 FROM civicrm_pcp_block pb
770 WHERE pb.is_active = 1 AND
771 pb.entity_id = %1 AND
772 pb.entity_table = %2";
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 /**
781 * Find out if the PCP block is in use by one or more PCP page.
782 *
783 * @param int $id
784 * Pcp block id.
785 *
786 * @return Bool
787 */
788 public static function getPcpBlockInUse($id) {
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 /**
800 * Get email is enabled for supporter's profile
801 *
802 * @param int $profileId
803 * Supporter's profile id.
804 *
805 * @return bool
806 */
807 public static function checkEmailProfile($profileId) {
808 $query = "
809 SELECT field_name
810 FROM civicrm_uf_field
811 WHERE 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 /**
822 * Obtain the title of page associated with a pcp.
823 *
824 * @param int $pcpId
825 * @param $component
826 *
827 * @return int
828 */
829 public static function getPcpPageTitle($pcpId, $component) {
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 /**
850 * Get pcp block & entity id given pcp id
851 *
852 * @param int $pcpId
853 * @param $component
854 *
855 * @return string
856 */
857 public static function getPcpBlockEntityId($pcpId, $component) {
858 $entity_table = self::getPcpEntityTable($component);
859
860 $query = "
861 SELECT pb.id as pcpBlockId, pb.entity_id
862 FROM civicrm_pcp pcp
863 LEFT JOIN civicrm_pcp_block pb ON ( pb.entity_id = pcp.page_id AND pb.entity_table = %2 )
864 WHERE 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 /**
876 * Get pcp entity table given a component.
877 *
878 * @param $component
879 *
880 * @return string
881 */
882 public static function getPcpEntityTable($component) {
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 /**
893 * Get supporter profile id.
894 *
895 * @param int $component_id
896 * @param string $component
897 *
898 * @return int
899 */
900 public static function getSupporterProfileId($component_id, $component = 'contribute') {
901 $entity_table = self::getPcpEntityTable($component);
902
903 $query = "
904 SELECT pcp.supporter_profile_id
905 FROM civicrm_pcp_block pcp
906 INNER 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 }
920
921 /**
922 * Get owner notification id.
923 *
924 * @param int $component_id
925 * @param $component
926 *
927 * @return int
928 */
929 public static function getOwnerNotificationId($component_id, $component = 'contribute') {
930 $entity_table = self::getPcpEntityTable($component);
931 $query = "
932 SELECT pb.owner_notify_id
933 FROM civicrm_pcp_block pb
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 }
942 }
943
944 }