3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Campaign_BAO_Petition
extends CRM_Campaign_BAO_Survey
{
36 function __construct() {
37 parent
::__construct();
38 // expire cookie in one day
39 $this->cookieExpire
= (1 * 60 * 60 * 24);
43 * Function to get Petition Details for dashboard.
47 static function getPetitionSummary($params = array(), $onlyCount = FALSE) {
48 //build the limit and order clause.
49 $limitClause = $orderByClause = $lookupTableJoins = NULL;
52 'sort' => 'created_date',
55 'sortOrder' => 'desc',
57 foreach ($sortParams as $name => $default) {
58 if (!empty($params[$name])) {
59 $sortParams[$name] = $params[$name];
63 //need to lookup tables.
64 $orderOnPetitionTable = TRUE;
65 if ($sortParams['sort'] == 'campaign') {
66 $orderOnPetitionTable = FALSE;
68 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = petition.campaign_id )';
69 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
71 elseif ($sortParams['sort'] == 'activity_type') {
72 $orderOnPetitionTable = FALSE;
74 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = petition.activity_type_id
75 OR petition.activity_type_id IS NULL )
76 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
77 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
79 elseif ($sortParams['sort'] == 'isActive') {
80 $sortParams['sort'] = 'is_active';
82 if ($orderOnPetitionTable) {
83 $orderByClause = "ORDER BY petition.{$sortParams['sort']} {$sortParams['sortOrder']}";
85 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
88 //build the where clause.
89 $queryParams = $where = array();
91 //we only have activity type as a
92 //difference between survey and petition.
93 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
94 if ($petitionTypeID) {
95 $where[] = "( petition.activity_type_id = %1 )";
96 $queryParams[1] = array($petitionTypeID, 'Positive');
98 if (!empty($params['title'])) {
99 $where[] = "( petition.title LIKE %2 )";
100 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
102 if (!empty($params['campaign_id'])) {
103 $where[] = '( petition.campaign_id = %3 )';
104 $queryParams[3] = array($params['campaign_id'], 'Positive');
107 if (!empty($where)) {
108 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
112 SELECT petition.id as id,
113 petition.title as title,
114 petition.is_active as is_active,
115 petition.result_id as result_id,
116 petition.is_default as is_default,
117 petition.campaign_id as campaign_id,
118 petition.activity_type_id as activity_type_id';
121 $selectClause = 'SELECT COUNT(*)';
123 $fromClause = 'FROM civicrm_survey petition';
125 $query = "{$selectClause} {$fromClause} {$whereClause} {$orderByClause} {$limitClause}";
128 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
131 $petitions = array();
142 $petition = CRM_Core_DAO
::executeQuery($query, $queryParams);
143 while ($petition->fetch()) {
144 foreach ($properties as $property) {
145 $petitions[$petition->id
][$property] = $petition->$property;
153 * Get the petition count.
157 static function getPetitionCount() {
158 $whereClause = 'WHERE ( 1 )';
159 $queryParams = array();
160 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
161 if ($petitionTypeID) {
162 $whereClause = "WHERE ( petition.activity_type_id = %1 )";
163 $queryParams[1] = array($petitionTypeID, 'Positive');
165 $query = "SELECT COUNT(*) FROM civicrm_survey petition {$whereClause}";
167 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
171 * takes an associative array and creates a petition signature activity
173 * @param array $params (reference ) an assoc array of name/value pairs
175 * @return object CRM_Campaign_BAO_Petition
179 function createSignature(&$params) {
180 if (empty($params)) {
184 if (!isset($params['sid'])) {
185 $statusMsg = ts('No survey sid parameter. Cannot process signature.');
186 CRM_Core_Session
::setStatus($statusMsg, ts('Sorry'), 'error');
190 if (isset($params['contactId'])) {
192 // add signature as activity with survey id as source id
193 // get the activity type id associated with this survey
194 $surveyInfo = CRM_Campaign_BAO_Petition
::getSurveyInfo($params['sid']);
197 // 1-Schedule, 2-Completed
199 $activityParams = array(
200 'source_contact_id' => $params['contactId'],
201 'target_contact_id' => $params['contactId'],
202 'source_record_id' => $params['sid'],
203 'subject' => $surveyInfo['title'],
204 'activity_type_id' => $surveyInfo['activity_type_id'],
205 'activity_date_time' => date("YmdHis"),
206 'status_id' => $params['statusId'],
207 'activity_campaign_id' => $params['activity_campaign_id'],
211 // *** check for activity using source id - if already signed
212 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
214 // save activity custom data
215 if (!empty($params['custom']) &&
216 is_array($params['custom'])
218 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $activity->id
);
221 // set permanent cookie to indicate this petition already signed on the computer
222 setcookie('signed_' . $params['sid'], $activity->id
, time() +
$this->cookieExpire
, '/');
228 function confirmSignature($activity_id, $contact_id, $petition_id) {
229 // change activity status to completed (status_id = 2)
230 // I wonder why do we need contact_id when we have activity_id anyway? [chastell]
231 $sql = 'UPDATE civicrm_activity SET status_id = 2 WHERE id = %1';
232 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
233 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
235 1 => array($activity_id, 'Integer'),
236 2 => array($contact_id, 'Integer'),
237 3 => array($sourceID, 'Integer')
239 CRM_Core_DAO
::executeQuery($sql, $params);
241 $sql = 'UPDATE civicrm_activity_contact SET contact_id = %2 WHERE activity_id = %1 AND record_type_id = %3';
242 CRM_Core_DAO
::executeQuery($sql, $params);
243 // remove 'Unconfirmed' tag for this contact
244 $tag_name = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
251 DELETE FROM civicrm_entity_tag
252 WHERE entity_table = 'civicrm_contact'
254 AND tag_id = ( SELECT id FROM civicrm_tag WHERE name = %2 )";
256 1 => array($contact_id, 'Integer'),
257 2 => array($tag_name, 'String'),
259 CRM_Core_DAO
::executeQuery($sql, $params);
261 // set permanent cookie to indicate this users email address now confirmed
262 setcookie("confirmed_{$petition_id}",
264 time() +
$this->cookieExpire
,
272 * Function to get Petition Signature Total
277 * @internal param bool $all
278 * @internal param int $id
281 static function getPetitionSignatureTotalbyCountry($surveyId) {
282 $countries = array();
284 SELECT count(civicrm_address.country_id) as total,
285 IFNULL(country_id,'') as country_id,IFNULL(iso_code,'') as country_iso, IFNULL(civicrm_country.name,'') as country
286 FROM ( civicrm_activity a, civicrm_survey, civicrm_contact )
287 LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1
288 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
289 LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id AND ac.record_type_id = %2 )
291 ac.contact_id = civicrm_contact.id AND
292 a.activity_type_id = civicrm_survey.activity_type_id AND
293 civicrm_survey.id = %1 AND
294 a.source_record_id = %1 ";
296 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
297 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
299 1 => array($surveyId, 'Integer'),
300 2 => array($sourceID, 'Integer')
302 $sql .= " GROUP BY civicrm_address.country_id";
303 $fields = array('total', 'country_id', 'country_iso', 'country');
305 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
306 while ($dao->fetch()) {
308 foreach ($fields as $field) {
309 $row[$field] = $dao->$field;
317 * Function to get Petition Signature Total
322 * @internal param bool $all
323 * @internal param int $id
326 static function getPetitionSignatureTotal($surveyId) {
327 $surveyInfo = CRM_Campaign_BAO_Petition
::getSurveyInfo((int) $surveyId);
328 //$activityTypeID = $surveyInfo['activity_type_id'];
331 status_id,count(id) as total
332 FROM civicrm_activity
334 source_record_id = " . (int) $surveyId . " AND activity_type_id = " . (int) $surveyInfo['activity_type_id'] . " GROUP BY status_id";
336 $statusTotal = array();
338 $dao = CRM_Core_DAO
::executeQuery($sql);
339 while ($dao->fetch()) {
340 $total +
= $dao->total
;
341 $statusTotal['status'][$dao->status_id
] = $dao->total
;
343 $statusTotal['count'] = $total;
348 public static function getSurveyInfo($surveyId = NULL) {
349 $surveyInfo = array();
352 SELECT activity_type_id,
355 ov.label AS activity_type
356 FROM civicrm_survey s, civicrm_option_value ov, civicrm_option_group og
357 WHERE s.id = " . (int) $surveyId . "
358 AND s.activity_type_id = ov.value
359 AND ov.option_group_id = og.id
360 AND og.name = 'activity_type'";
362 $dao = CRM_Core_DAO
::executeQuery($sql);
363 while ($dao->fetch()) {
364 //$survey['campaign_id'] = $dao->campaign_id;
365 //$survey['campaign_name'] = $dao->campaign_name;
366 $surveyInfo['activity_type'] = $dao->activity_type
;
367 $surveyInfo['activity_type_id'] = $dao->activity_type_id
;
368 $surveyInfo['title'] = $dao->title
;
375 * Function to get Petition Signature Details
378 * @param null $status_id
381 * @internal param bool $all
382 * @internal param int $id
385 static function getPetitionSignature($surveyId, $status_id = NULL) {
387 // sql injection protection
388 $surveyId = (int) $surveyId;
389 $signature = array();
393 a.source_record_id as survey_id,
394 a.activity_date_time,
396 civicrm_contact.id as contact_id,
397 civicrm_contact.contact_type,civicrm_contact.contact_sub_type,image_URL,
398 first_name,last_name,sort_name,
399 employer_id,organization_name,
401 IFNULL(gender_id,'') AS gender_id,
402 IFNULL(state_province_id,'') AS state_province_id,
403 IFNULL(country_id,'') as country_id,IFNULL(iso_code,'') as country_iso, IFNULL(civicrm_country.name,'') as country
404 FROM (civicrm_activity a, civicrm_survey, civicrm_contact )
405 LEFT JOIN civicrm_activity_contact ac ON ( ac.activity_id = a.id AND ac.record_type_id = %3 )
406 LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1
407 LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
409 ac.contact_id = civicrm_contact.id AND
410 a.activity_type_id = civicrm_survey.activity_type_id AND
411 civicrm_survey.id = %1 AND
412 a.source_record_id = %1 ";
414 $params = array(1 => array($surveyId, 'Integer'));
417 $sql .= " AND status_id = %2";
418 $params[2] = array($status_id, 'Integer');
420 $sql .= " ORDER BY a.activity_date_time";
422 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
423 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
424 $params[3] = array($sourceID, 'Integer');
430 'activity_date_time',
443 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
444 while ($dao->fetch()) {
446 foreach ($fields as $field) {
447 $row[$field] = $dao->$field;
455 * This function returns all entities assigned to a specific tag
457 * @param object $tag an object of a tag.
459 * @return array $contactIds array of contact ids
462 function getEntitiesByTag($tag) {
463 $contactIds = array();
464 $entityTagDAO = new CRM_Core_DAO_EntityTag();
465 $entityTagDAO->tag_id
= $tag['id'];
466 $entityTagDAO->find();
468 while ($entityTagDAO->fetch()) {
469 $contactIds[] = $entityTagDAO->entity_id
;
475 * Function to check if contact has signed this petition
477 * @param int $surveyId
478 * @param int $contactId
483 static function checkSignature($surveyId, $contactId) {
485 $surveyInfo = CRM_Campaign_BAO_Petition
::getSurveyInfo($surveyId);
486 $signature = array();
487 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
488 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
492 a.source_record_id AS source_record_id,
493 ac.contact_id AS source_contact_id,
494 a.activity_date_time AS activity_date_time,
495 a.activity_type_id AS activity_type_id,
496 a.status_id AS status_id,
498 FROM civicrm_activity a
499 INNER JOIN civicrm_activity_contact ac ON (ac.activity_id = a.id AND ac.record_type_id = %5)
500 WHERE a.source_record_id = %2
501 AND a.activity_type_id = %3
502 AND ac.contact_id = %4
505 1 => array($surveyInfo['title'], 'String'),
506 2 => array($surveyId, 'Integer'),
507 3 => array($surveyInfo['activity_type_id'], 'Integer'),
508 4 => array($contactId, 'Integer'),
509 5 => array($sourceID, 'Integer')
512 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
513 while ($dao->fetch()) {
514 $signature[$dao->id
]['id'] = $dao->id
;
515 $signature[$dao->id
]['source_record_id'] = $dao->source_record_id
;
516 $signature[$dao->id
]['source_contact_id'] = CRM_Contact_BAO_Contact
::displayName($dao->source_contact_id
);
517 $signature[$dao->id
]['activity_date_time'] = $dao->activity_date_time
;
518 $signature[$dao->id
]['activity_type_id'] = $dao->activity_type_id
;
519 $signature[$dao->id
]['status_id'] = $dao->status_id
;
520 $signature[$dao->id
]['survey_title'] = $dao->survey_title
;
521 $signature[$dao->id
]['contactId'] = $dao->source_contact_id
;
528 * takes an associative array and sends a thank you or email verification email
530 * @param array $params (reference ) an assoc array of name/value pairs
532 * @param $sendEmailMode
539 public static function sendEmail($params, $sendEmailMode) {
542 * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
543 * connected user via login/pwd - thank you
544 * or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
545 * or login using fb connect - thank you + click to add msg to fb wall
547 * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
548 * send a confirmation request email
551 // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
552 $petitionGroupName = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
558 $dao = new CRM_Contact_DAO_Group();
559 $dao->title
= $petitionGroupName;
560 if (!$dao->find(TRUE)) {
562 $dao->visibility
= 'User and User Admin Only';
565 $group_id = $dao->id
;
568 $petitionParams['id'] = $params['sid'];
569 $petitionInfo = array();
570 CRM_Campaign_BAO_Survey
::retrieve($petitionParams, $petitionInfo);
571 if (empty($petitionInfo)) {
572 CRM_Core_Error
::fatal('Petition doesn\'t exist.');
575 //get the default domain email address.
576 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain
::getNameAndEmail();
578 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
580 $toName = CRM_Contact_BAO_Contact
::displayName($params['contactId']);
582 $replyTo = "do-not-reply@$emailDomain";
584 // set additional general message template params (custom tokens to use in email msg templates)
585 // tokens then available in msg template as {$petition.title}, etc
586 $petitionTokens['title'] = $petitionInfo['title'];
587 $petitionTokens['petitionId'] = $params['sid'];
588 $tplParams['petition'] = $petitionTokens;
590 switch ($sendEmailMode) {
591 case CRM_Campaign_Form_Petition_Signature
::EMAIL_THANK
:
593 // add this contact to the CIVICRM_PETITION_CONTACTS group
594 // Cannot pass parameter 1 by reference
595 $p = array($params['contactId']);
596 CRM_Contact_BAO_GroupContact
::addContactsToGroup($p, $group_id, 'API');
598 if ($params['email-Primary']) {
599 CRM_Core_BAO_MessageTemplate
::sendTemplate(
601 'groupName' => 'msg_tpl_workflow_petition',
602 'valueName' => 'petition_sign',
603 'contactId' => $params['contactId'],
604 'tplParams' => $tplParams,
605 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
607 'toEmail' => $params['email-Primary'],
608 'replyTo' => $replyTo,
609 'petitionId' => $params['sid'],
610 'petitionTitle' => $petitionInfo['title'],
616 case CRM_Campaign_Form_Petition_Signature
::EMAIL_CONFIRM
:
617 // create mailing event subscription record for this contact
618 // this will allow using a hash key to confirm email address by sending a url link
619 $se = CRM_Mailing_Event_BAO_Subscribe
::subscribe($group_id,
620 $params['email-Primary'],
621 $params['contactId'],
625 // require_once 'CRM/Core/BAO/Domain.php';
626 // $domain = CRM_Core_BAO_Domain::getDomain();
627 $config = CRM_Core_Config
::singleton();
628 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
630 $replyTo = implode($config->verpSeparator
,
640 $confirmUrl = CRM_Utils_System
::url('civicrm/petition/confirm',
641 "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}",
644 $confirmUrlPlainText = CRM_Utils_System
::url('civicrm/petition/confirm',
645 "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}",
651 // set email specific message template params and assign to tplParams
652 $petitionTokens['confirmUrl'] = $confirmUrl;
653 $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
654 $tplParams['petition'] = $petitionTokens;
656 if ($params['email-Primary']) {
657 CRM_Core_BAO_MessageTemplate
::sendTemplate(
659 'groupName' => 'msg_tpl_workflow_petition',
660 'valueName' => 'petition_confirmation_needed',
661 'contactId' => $params['contactId'],
662 'tplParams' => $tplParams,
663 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
665 'toEmail' => $params['email-Primary'],
666 'replyTo' => $replyTo,
667 'petitionId' => $params['sid'],
668 'petitionTitle' => $petitionInfo['title'],
669 'confirmUrl' => $confirmUrl,