3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Campaign_BAO_Petition
extends CRM_Campaign_BAO_Survey
{
38 public function __construct() {
39 parent
::__construct();
40 // expire cookie in one day
41 $this->cookieExpire
= (1 * 60 * 60 * 24);
45 * Get Petition Details for dashboard.
47 * @param array $params
48 * @param bool $onlyCount
52 public static function getPetitionSummary($params = [], $onlyCount = FALSE) {
53 //build the limit and order clause.
54 $limitClause = $orderByClause = $lookupTableJoins = NULL;
57 'sort' => 'created_date',
60 'sortOrder' => 'desc',
62 foreach ($sortParams as $name => $default) {
63 if (!empty($params[$name])) {
64 $sortParams[$name] = $params[$name];
68 //need to lookup tables.
69 $orderOnPetitionTable = TRUE;
70 if ($sortParams['sort'] == 'campaign') {
71 $orderOnPetitionTable = FALSE;
73 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = petition.campaign_id )';
74 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
76 elseif ($sortParams['sort'] == 'activity_type') {
77 $orderOnPetitionTable = FALSE;
79 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = petition.activity_type_id
80 OR petition.activity_type_id IS NULL )
81 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
82 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
84 elseif ($sortParams['sort'] == 'isActive') {
85 $sortParams['sort'] = 'is_active';
87 if ($orderOnPetitionTable) {
88 $orderByClause = "ORDER BY petition.{$sortParams['sort']} {$sortParams['sortOrder']}";
90 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
93 //build the where clause.
94 $queryParams = $where = [];
96 //we only have activity type as a
97 //difference between survey and petition.
98 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
99 if ($petitionTypeID) {
100 $where[] = "( petition.activity_type_id = %1 )";
101 $queryParams[1] = [$petitionTypeID, 'Positive'];
103 if (!empty($params['title'])) {
104 $where[] = "( petition.title LIKE %2 )";
105 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
107 if (!empty($params['campaign_id'])) {
108 $where[] = '( petition.campaign_id = %3 )';
109 $queryParams[3] = [$params['campaign_id'], 'Positive'];
112 if (!empty($where)) {
113 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
117 SELECT petition.id as id,
118 petition.title as title,
119 petition.is_active as is_active,
120 petition.result_id as result_id,
121 petition.is_default as is_default,
122 petition.campaign_id as campaign_id,
123 petition.activity_type_id as activity_type_id';
126 $selectClause = 'SELECT COUNT(*)';
128 $fromClause = 'FROM civicrm_survey petition';
130 $query = "{$selectClause} {$fromClause} {$whereClause} {$orderByClause} {$limitClause}";
133 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
147 $petition = CRM_Core_DAO
::executeQuery($query, $queryParams);
148 while ($petition->fetch()) {
149 foreach ($properties as $property) {
150 $petitions[$petition->id
][$property] = $petition->$property;
158 * Get the petition count.
161 public static function getPetitionCount() {
162 $whereClause = 'WHERE ( 1 )';
164 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
165 if ($petitionTypeID) {
166 $whereClause = "WHERE ( petition.activity_type_id = %1 )";
167 $queryParams[1] = [$petitionTypeID, 'Positive'];
169 $query = "SELECT COUNT(*) FROM civicrm_survey petition {$whereClause}";
171 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
175 * Takes an associative array and creates a petition signature activity.
177 * @param array $params
178 * (reference ) an assoc array of name/value pairs.
181 * CRM_Campaign_BAO_Petition or NULl or void
183 public function createSignature(&$params) {
184 if (empty($params)) {
188 if (!isset($params['sid'])) {
189 $statusMsg = ts('No survey sid parameter. Cannot process signature.');
190 CRM_Core_Session
::setStatus($statusMsg, ts('Sorry'), 'error');
194 if (isset($params['contactId'])) {
196 // add signature as activity with survey id as source id
197 // get the activity type id associated with this survey
198 $surveyInfo = CRM_Campaign_BAO_Petition
::getSurveyInfo($params['sid']);
201 // 1-Schedule, 2-Completed
204 'source_contact_id' => $params['contactId'],
205 'target_contact_id' => $params['contactId'],
206 'source_record_id' => $params['sid'],
207 'subject' => $surveyInfo['title'],
208 'activity_type_id' => $surveyInfo['activity_type_id'],
209 'activity_date_time' => date("YmdHis"),
210 'status_id' => $params['statusId'],
211 'activity_campaign_id' => $params['activity_campaign_id'],
215 // *** check for activity using source id - if already signed
216 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
218 // save activity custom data
219 if (!empty($params['custom']) &&
220 is_array($params['custom'])
222 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $activity->id
);
225 // Set browser cookie to indicate this petition was already signed.
226 $config = CRM_Core_Config
::singleton();
227 $url_parts = parse_url($config->userFrameworkBaseURL
);
228 setcookie('signed_' . $params['sid'], $activity->id
, time() +
$this->cookieExpire
, $url_parts['path'], $url_parts['host'], CRM_Utils_System
::isSSL());
235 * @param int $activity_id
236 * @param int $contact_id
237 * @param int $petition_id
241 public function confirmSignature($activity_id, $contact_id, $petition_id) {
242 // change activity status to completed (status_id = 2)
243 // I wonder why do we need contact_id when we have activity_id anyway? [chastell]
244 $sql = 'UPDATE civicrm_activity SET status_id = 2 WHERE id = %1';
245 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
246 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
248 1 => [$activity_id, 'Integer'],
249 2 => [$contact_id, 'Integer'],
250 3 => [$sourceID, 'Integer'],
252 CRM_Core_DAO
::executeQuery($sql, $params);
254 $sql = 'UPDATE civicrm_activity_contact SET contact_id = %2 WHERE activity_id = %1 AND record_type_id = %3';
255 CRM_Core_DAO
::executeQuery($sql, $params);
256 // remove 'Unconfirmed' tag for this contact
257 $tag_name = Civi
::settings()->get('tag_unconfirmed');
260 DELETE FROM civicrm_entity_tag
261 WHERE entity_table = 'civicrm_contact'
263 AND tag_id = ( SELECT id FROM civicrm_tag WHERE name = %2 )";
265 1 => [$contact_id, 'Integer'],
266 2 => [$tag_name, 'String'],
268 CRM_Core_DAO
::executeQuery($sql, $params);
269 // validate arguments to setcookie are numeric to prevent header manipulation
270 if (isset($petition_id) && is_numeric($petition_id)
271 && isset($activity_id) && is_numeric($activity_id)) {
272 // set permanent cookie to indicate this users email address now confirmed
273 $config = CRM_Core_Config
::singleton();
274 $url_parts = parse_url($config->userFrameworkBaseURL
);
275 setcookie("confirmed_{$petition_id}",
277 time() +
$this->cookieExpire
,
280 CRM_Utils_System
::isSSL()
285 CRM_Core_Error
::fatal(ts('Petition Id and/or Activity Id is not of the type Positive.'));
291 * Get Petition Signature Total.
293 * @param int $surveyId
297 public static function getPetitionSignatureTotalbyCountry($surveyId) {
300 SELECT count(civicrm_address.country_id) as total,
301 IFNULL(country_id,'') as country_id,IFNULL(iso_code,'') as country_iso, IFNULL(civicrm_country.name,'') as country
302 FROM ( civicrm_activity a, civicrm_survey, civicrm_contact )
303 LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1
304 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
305 LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id AND ac.record_type_id = %2 )
307 ac.contact_id = civicrm_contact.id AND
308 a.activity_type_id = civicrm_survey.activity_type_id AND
309 civicrm_survey.id = %1 AND
310 a.source_record_id = %1 ";
312 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
313 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
315 1 => [$surveyId, 'Integer'],
316 2 => [$sourceID, 'Integer'],
318 $sql .= " GROUP BY civicrm_address.country_id";
319 $fields = ['total', 'country_id', 'country_iso', 'country'];
321 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
322 while ($dao->fetch()) {
324 foreach ($fields as $field) {
325 $row[$field] = $dao->$field;
333 * Get Petition Signature Total.
335 * @param int $surveyId
339 public static function getPetitionSignatureTotal($surveyId) {
340 $surveyInfo = CRM_Campaign_BAO_Petition
::getSurveyInfo((int) $surveyId);
341 //$activityTypeID = $surveyInfo['activity_type_id'];
344 status_id,count(id) as total
345 FROM civicrm_activity
347 source_record_id = " . (int) $surveyId . " AND activity_type_id = " . (int) $surveyInfo['activity_type_id'] . " GROUP BY status_id";
351 $dao = CRM_Core_DAO
::executeQuery($sql);
352 while ($dao->fetch()) {
353 $total +
= $dao->total
;
354 $statusTotal['status'][$dao->status_id
] = $dao->total
;
356 $statusTotal['count'] = $total;
361 * @param int $surveyId
365 public static function getSurveyInfo($surveyId = NULL) {
369 SELECT activity_type_id,
372 ov.label AS activity_type
373 FROM civicrm_survey s, civicrm_option_value ov, civicrm_option_group og
374 WHERE s.id = " . (int) $surveyId . "
375 AND s.activity_type_id = ov.value
376 AND ov.option_group_id = og.id
377 AND og.name = 'activity_type'";
379 $dao = CRM_Core_DAO
::executeQuery($sql);
380 while ($dao->fetch()) {
381 //$survey['campaign_id'] = $dao->campaign_id;
382 //$survey['campaign_name'] = $dao->campaign_name;
383 $surveyInfo['activity_type'] = $dao->activity_type
;
384 $surveyInfo['activity_type_id'] = $dao->activity_type_id
;
385 $surveyInfo['title'] = $dao->title
;
392 * Get Petition Signature Details.
394 * @param int $surveyId
395 * @param int $status_id
399 public static function getPetitionSignature($surveyId, $status_id = NULL) {
401 // sql injection protection
402 $surveyId = (int) $surveyId;
407 a.source_record_id as survey_id,
408 a.activity_date_time,
410 civicrm_contact.id as contact_id,
411 civicrm_contact.contact_type,civicrm_contact.contact_sub_type,image_URL,
412 first_name,last_name,sort_name,
413 employer_id,organization_name,
415 IFNULL(gender_id,'') AS gender_id,
416 IFNULL(state_province_id,'') AS state_province_id,
417 IFNULL(country_id,'') as country_id,IFNULL(iso_code,'') as country_iso, IFNULL(civicrm_country.name,'') as country
418 FROM (civicrm_activity a, civicrm_survey, civicrm_contact )
419 LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id AND ac.record_type_id = %3 )
420 LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1
421 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
423 ac.contact_id = civicrm_contact.id AND
424 a.activity_type_id = civicrm_survey.activity_type_id AND
425 civicrm_survey.id = %1 AND
426 a.source_record_id = %1 ";
428 $params = [1 => [$surveyId, 'Integer']];
431 $sql .= " AND status_id = %2";
432 $params[2] = [$status_id, 'Integer'];
434 $sql .= " ORDER BY a.activity_date_time";
436 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
437 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
438 $params[3] = [$sourceID, 'Integer'];
444 'activity_date_time',
457 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
458 while ($dao->fetch()) {
460 foreach ($fields as $field) {
461 $row[$field] = $dao->$field;
469 * This function returns all entities assigned to a specific tag.
472 * An object of a tag.
475 * array of contact ids
477 public function getEntitiesByTag($tag) {
479 $entityTagDAO = new CRM_Core_DAO_EntityTag();
480 $entityTagDAO->tag_id
= $tag['id'];
481 $entityTagDAO->find();
483 while ($entityTagDAO->fetch()) {
484 $contactIds[] = $entityTagDAO->entity_id
;
490 * Check if contact has signed this petition.
492 * @param int $surveyId
493 * @param int $contactId
497 public static function checkSignature($surveyId, $contactId) {
499 $surveyInfo = CRM_Campaign_BAO_Petition
::getSurveyInfo($surveyId);
501 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
502 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
506 a.source_record_id AS source_record_id,
507 ac.contact_id AS source_contact_id,
508 a.activity_date_time AS activity_date_time,
509 a.activity_type_id AS activity_type_id,
510 a.status_id AS status_id,
512 FROM civicrm_activity a
513 INNER JOIN civicrm_activity_contact ac ON (ac.activity_id = a.id AND ac.record_type_id = %5)
514 WHERE a.source_record_id = %2
515 AND a.activity_type_id = %3
516 AND ac.contact_id = %4
519 1 => [$surveyInfo['title'], 'String'],
520 2 => [$surveyId, 'Integer'],
521 3 => [$surveyInfo['activity_type_id'], 'Integer'],
522 4 => [$contactId, 'Integer'],
523 5 => [$sourceID, 'Integer'],
526 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
527 while ($dao->fetch()) {
528 $signature[$dao->id
]['id'] = $dao->id
;
529 $signature[$dao->id
]['source_record_id'] = $dao->source_record_id
;
530 $signature[$dao->id
]['source_contact_id'] = CRM_Contact_BAO_Contact
::displayName($dao->source_contact_id
);
531 $signature[$dao->id
]['activity_date_time'] = $dao->activity_date_time
;
532 $signature[$dao->id
]['activity_type_id'] = $dao->activity_type_id
;
533 $signature[$dao->id
]['status_id'] = $dao->status_id
;
534 $signature[$dao->id
]['survey_title'] = $dao->survey_title
;
535 $signature[$dao->id
]['contactId'] = $dao->source_contact_id
;
542 * Takes an associative array and sends a thank you or email verification email.
544 * @param array $params
545 * (reference ) an assoc array of name/value pairs.
547 * @param int $sendEmailMode
551 public static function sendEmail($params, $sendEmailMode) {
554 * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
555 * connected user via login/pwd - thank you
556 * or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
557 * or login using fb connect - thank you + click to add msg to fb wall
559 * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
560 * send a confirmation request email
563 // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
564 $petitionGroupName = Civi
::settings()->get('petition_contacts');
566 $dao = new CRM_Contact_DAO_Group();
567 $dao->title
= $petitionGroupName;
568 if (!$dao->find(TRUE)) {
570 $dao->visibility
= 'User and User Admin Only';
573 $group_id = $dao->id
;
576 $petitionParams['id'] = $params['sid'];
578 CRM_Campaign_BAO_Survey
::retrieve($petitionParams, $petitionInfo);
579 if (empty($petitionInfo)) {
580 CRM_Core_Error
::fatal('Petition doesn\'t exist.');
583 //get the default domain email address.
584 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain
::getNameAndEmail();
586 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
588 $toName = CRM_Contact_BAO_Contact
::displayName($params['contactId']);
590 $replyTo = CRM_Core_BAO_Domain
::getNoReplyEmailAddress();
592 // set additional general message template params (custom tokens to use in email msg templates)
593 // tokens then available in msg template as {$petition.title}, etc
594 $petitionTokens['title'] = $petitionInfo['title'];
595 $petitionTokens['petitionId'] = $params['sid'];
596 $tplParams['petition'] = $petitionTokens;
598 switch ($sendEmailMode) {
599 case CRM_Campaign_Form_Petition_Signature
::EMAIL_THANK
:
601 // add this contact to the CIVICRM_PETITION_CONTACTS group
602 // Cannot pass parameter 1 by reference
603 $p = [$params['contactId']];
604 CRM_Contact_BAO_GroupContact
::addContactsToGroup($p, $group_id, 'API');
606 if ($params['email-Primary']) {
607 CRM_Core_BAO_MessageTemplate
::sendTemplate(
609 'groupName' => 'msg_tpl_workflow_petition',
610 'valueName' => 'petition_sign',
611 'contactId' => $params['contactId'],
612 'tplParams' => $tplParams,
613 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
615 'toEmail' => $params['email-Primary'],
616 'replyTo' => $replyTo,
617 'petitionId' => $params['sid'],
618 'petitionTitle' => $petitionInfo['title'],
624 case CRM_Campaign_Form_Petition_Signature
::EMAIL_CONFIRM
:
625 // create mailing event subscription record for this contact
626 // this will allow using a hash key to confirm email address by sending a url link
627 $se = CRM_Mailing_Event_BAO_Subscribe
::subscribe($group_id,
628 $params['email-Primary'],
629 $params['contactId'],
633 // require_once 'CRM/Core/BAO/Domain.php';
634 // $domain = CRM_Core_BAO_Domain::getDomain();
635 $config = CRM_Core_Config
::singleton();
636 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
638 $replyTo = implode($config->verpSeparator
,
647 $confirmUrl = CRM_Utils_System
::url('civicrm/petition/confirm',
648 "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&pid={$params['sid']}",
651 $confirmUrlPlainText = CRM_Utils_System
::url('civicrm/petition/confirm',
652 "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&pid={$params['sid']}",
658 // set email specific message template params and assign to tplParams
659 $petitionTokens['confirmUrl'] = $confirmUrl;
660 $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
661 $tplParams['petition'] = $petitionTokens;
663 if ($params['email-Primary']) {
664 CRM_Core_BAO_MessageTemplate
::sendTemplate(
666 'groupName' => 'msg_tpl_workflow_petition',
667 'valueName' => 'petition_confirmation_needed',
668 'contactId' => $params['contactId'],
669 'tplParams' => $tplParams,
670 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
672 'toEmail' => $params['email-Primary'],
673 'replyTo' => $replyTo,
674 'petitionId' => $params['sid'],
675 'petitionTitle' => $petitionInfo['title'],
676 'confirmUrl' => $confirmUrl,