3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Class CRM_Campaign_BAO_Survey.
21 class CRM_Campaign_BAO_Survey
extends CRM_Campaign_DAO_Survey
{
24 * Retrieve DB object based on input parameters.
26 * It also stores all the retrieved values in the default array.
28 * @param array $params
29 * (reference ) an assoc array of name/value pairs.
30 * @param array $defaults
31 * (reference ) an assoc array to hold the flattened values.
33 * @return CRM_Campaign_DAO_Survey|null
35 public static function retrieve(&$params, &$defaults) {
36 $dao = new CRM_Campaign_DAO_Survey();
38 $dao->copyValues($params);
40 if ($dao->find(TRUE)) {
41 CRM_Core_DAO
::storeValues($dao, $defaults);
48 * Takes an associative array and creates a Survey object based on the
51 * @param array $params
53 * @return bool|CRM_Campaign_DAO_Survey
55 public static function create(&$params) {
60 if (!empty($params['is_default'])) {
61 $query = "UPDATE civicrm_survey SET is_default = 0";
62 CRM_Core_DAO
::executeQuery($query);
65 if (!(CRM_Utils_Array
::value('id', $params))) {
67 if (!(CRM_Utils_Array
::value('created_id', $params))) {
68 $session = CRM_Core_Session
::singleton();
69 $params['created_id'] = $session->get('userID');
71 if (!(CRM_Utils_Array
::value('created_date', $params))) {
72 $params['created_date'] = date('YmdHis');
75 CRM_Utils_Hook
::pre('create', 'Survey', NULL, $params);
78 CRM_Utils_Hook
::pre('edit', 'Survey', $params['id'], $params);
81 $dao = new CRM_Campaign_DAO_Survey();
82 $dao->copyValues($params);
85 if (!empty($params['id'])) {
86 CRM_Utils_Hook
::post('edit', 'Survey', $dao->id
, $dao);
89 CRM_Utils_Hook
::post('create', 'Survey', $dao->id
, $dao);
92 if (!empty($params['custom']) &&
93 is_array($params['custom'])
95 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
101 * Retrieve surveys for dashboard.
103 * @param array $params
104 * @param bool $onlyCount
108 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
109 //build the limit and order clause.
110 $limitClause = $orderByClause = $lookupTableJoins = NULL;
113 'sort' => 'created_date',
116 'sortOrder' => 'desc',
118 foreach ($sortParams as $name => $default) {
119 if (!empty($params[$name])) {
120 $sortParams[$name] = $params[$name];
124 //need to lookup tables.
125 $orderOnSurveyTable = TRUE;
126 if ($sortParams['sort'] == 'campaign') {
127 $orderOnSurveyTable = FALSE;
128 $lookupTableJoins = '
129 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
130 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
132 elseif ($sortParams['sort'] == 'activity_type') {
133 $orderOnSurveyTable = FALSE;
134 $lookupTableJoins = "
135 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
136 OR survey.activity_type_id IS NULL )
137 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
138 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
140 elseif ($sortParams['sort'] == 'isActive') {
141 $sortParams['sort'] = 'is_active';
143 if ($orderOnSurveyTable) {
144 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
146 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
149 //build the where clause.
150 $queryParams = $where = [];
152 //we only have activity type as a
153 //difference between survey and petition.
154 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
155 if ($petitionTypeID) {
156 $where[] = "( survey.activity_type_id != %1 )";
157 $queryParams[1] = [$petitionTypeID, 'Positive'];
160 if (!empty($params['title'])) {
161 $where[] = "( survey.title LIKE %2 )";
162 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
164 if (!empty($params['campaign_id'])) {
165 $where[] = '( survey.campaign_id = %3 )';
166 $queryParams[3] = [$params['campaign_id'], 'Positive'];
168 if (!empty($params['activity_type_id'])) {
169 $typeId = $params['activity_type_id'];
170 if (is_array($params['activity_type_id'])) {
171 $typeId = implode(' , ', $params['activity_type_id']);
173 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
176 if (!empty($where)) {
177 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
181 SELECT survey.id as id,
182 survey.title as title,
183 survey.is_active as is_active,
184 survey.result_id as result_id,
185 survey.is_default as is_default,
186 survey.campaign_id as campaign_id,
187 survey.activity_type_id as activity_type_id,
188 survey.release_frequency as release_frequency,
189 survey.max_number_of_contacts as max_number_of_contacts,
190 survey.default_number_of_contacts as default_number_of_contacts';
192 $selectClause = 'SELECT COUNT(*)';
194 $fromClause = 'FROM civicrm_survey survey';
196 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
200 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
213 'max_number_of_contacts',
214 'default_number_of_contacts',
217 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
218 while ($survey->fetch()) {
219 foreach ($properties as $property) {
220 $surveys[$survey->id
][$property] = $survey->$property;
228 * Get the survey count.
231 public static function getSurveyCount() {
232 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
238 * @param bool $onlyActive
239 * Retrieve only active surveys.
240 * @param bool $onlyDefault
241 * Retrieve only default survey.
242 * @param bool $forceAll
243 * Retrieve all surveys.
244 * @param bool $includePetition
245 * Include or exclude petitions.
248 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
250 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
251 foreach ($cacheKeyParams as $param) {
252 $cacheParam = $
$param;
256 $cacheKey .= '_' . $cacheParam;
261 if (!isset($surveys[$cacheKey])) {
262 if (!$includePetition) {
263 //we only have activity type as a
264 //difference between survey and petition.
265 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'petition');
268 if ($petitionTypeID) {
269 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
272 if (!$forceAll && $onlyActive) {
273 $where[] = '( survey.is_active = 1 )';
275 if (!$forceAll && $onlyDefault) {
276 $where[] = '( survey.is_default = 1 )';
278 $whereClause = implode(' AND ', $where);
281 SELECT survey.id as id,
282 survey.title as title
283 FROM civicrm_survey as survey
284 WHERE {$whereClause}";
285 $surveys[$cacheKey] = [];
286 $survey = CRM_Core_DAO
::executeQuery($query);
287 while ($survey->fetch()) {
288 $surveys[$cacheKey][$survey->id
] = $survey->title
;
292 return $surveys[$cacheKey];
296 * Get Survey activity types.
298 * @param string $returnColumn
299 * @param bool $includePetitionActivityType
303 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
304 static $activityTypes;
305 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
307 if (!isset($activityTypes[$cacheKey])) {
309 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
310 if ($campaignCompId) {
311 $condition = " AND v.component_id={$campaignCompId}";
312 if (!$includePetitionActivityType) {
313 $condition .= " AND v.name != 'Petition'";
315 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
322 if (!empty($activityTypes[$cacheKey])) {
323 return $activityTypes[$cacheKey];
331 * Get Surveys custom groups.
333 * @param array $surveyTypes
334 * an array of survey type id.
338 public static function getSurveyCustomGroups($surveyTypes = []) {
340 if (!is_array($surveyTypes)) {
341 $surveyTypes = [$surveyTypes];
344 if (!empty($surveyTypes)) {
345 $activityTypes = array_flip($surveyTypes);
348 $activityTypes = self
::getSurveyActivityType();
351 if (!empty($activityTypes)) {
352 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
354 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
355 FROM civicrm_custom_group cg
356 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
358 $dao = CRM_Core_DAO
::executeQuery($query);
359 while ($dao->fetch()) {
360 $customGroups[$dao->id
]['id'] = $dao->id
;
361 $customGroups[$dao->id
]['name'] = $dao->name
;
362 $customGroups[$dao->id
]['title'] = $dao->title
;
363 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
367 return $customGroups;
371 * Update the is_active flag in the db.
374 * Id of the database record.
375 * @param bool $is_active
376 * Value we want to set the is_active field.
379 * true if we found and updated the object, else false
381 public static function setIsActive($id, $is_active) {
382 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
393 public static function del($id) {
397 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
399 CRM_Report_BAO_ReportInstance
::del($reportId);
401 $dao = new CRM_Campaign_DAO_Survey();
403 return $dao->delete();
407 * This function retrieve contact information.
409 * @param array $voterIds
410 * @param array $returnProperties
411 * An array of return elements.
414 * array of contact info.
416 public static function voterDetails($voterIds, $returnProperties = []) {
418 if (!is_array($voterIds) ||
empty($voterIds)) {
419 return $voterDetails;
422 if (empty($returnProperties)) {
423 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
424 'contact_autocomplete_options'
426 $returnProperties = array_fill_keys(array_merge(
427 ['contact_type', 'contact_sub_type', 'sort_name'],
428 array_keys($autocompleteContactSearch)
432 $select = $from = [];
433 foreach ($returnProperties as $property => $ignore) {
434 $value = (in_array($property, [
437 ])) ?
'address' : $property;
441 case 'contact_sub_type':
442 $select[] = "$property as $property";
443 $from['contact'] = 'civicrm_contact contact';
449 case 'street_address':
450 $select[] = "$property as $property";
451 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
455 case 'state_province':
456 $select[] = "{$property}.name as $property";
457 if (!in_array('address', $from)) {
458 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
460 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
465 //finally retrieve contact details.
466 if (!empty($select) && !empty($from)) {
467 $fromClause = implode(' ', $from);
468 $selectClause = implode(', ', $select);
469 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
472 SELECT contact.id as contactId, $selectClause
476 $contact = CRM_Core_DAO
::executeQuery($query);
477 while ($contact->fetch()) {
478 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
479 foreach ($returnProperties as $property => $ignore) {
480 $voterDetails[$contact->contactId
][$property] = $contact->$property;
482 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
486 $voterDetails[$contact->contactId
]['contact_type'] = $image;
490 return $voterDetails;
494 * This function retrieve survey related activities w/ for give voter ids.
496 * @param int $surveyId
498 * @param array $voterIds
501 * @param int $interviewerId
502 * @param array $statusIds
505 * array of survey activity.
507 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
508 $activityDetails = [];
510 !is_array($voterIds) ||
empty($voterIds)
512 return $activityDetails;
516 if (is_array($statusIds) && !empty($statusIds)) {
517 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
520 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
521 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
522 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
523 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
525 $params[1] = [$surveyId, 'Integer'];
527 SELECT activity.id, activity.status_id,
528 activityTarget.contact_id as voter_id,
529 activityAssignment.contact_id as interviewer_id
530 FROM civicrm_activity activity
531 INNER JOIN civicrm_activity_contact activityTarget
532 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
533 INNER JOIN civicrm_activity_contact activityAssignment
534 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
535 WHERE activity.source_record_id = %1
536 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
537 if (!empty($interviewerId)) {
538 $query .= "AND activityAssignment.contact_id = %2 ";
539 $params[2] = [$interviewerId, 'Integer'];
541 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
543 $activity = CRM_Core_DAO
::executeQuery($query, $params);
544 while ($activity->fetch()) {
545 $activityDetails[$activity->voter_id
] = [
546 'voter_id' => $activity->voter_id
,
547 'status_id' => $activity->status_id
,
548 'activity_id' => $activity->id
,
549 'interviewer_id' => $activity->interviewer_id
,
553 return $activityDetails;
557 * This function retrieve survey related activities.
559 * @param int $surveyId
560 * @param int $interviewerId
561 * @param array $statusIds
562 * @param array $voterIds
563 * @param bool $onlyCount
566 * An array of survey activity.
568 public static function getSurveyActivities(
570 $interviewerId = NULL,
576 $surveyActivityCount = 0;
578 return ($onlyCount) ?
0 : $activities;
582 if (!empty($statusIds)) {
583 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
586 if ($interviewerId) {
587 $where[] = "( activityAssignment.contact_id = $interviewerId )";
590 if (!empty($voterIds)) {
591 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
595 if (!empty($where)) {
596 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
599 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
605 $select = "SELECT count(activity.id)";
609 SELECT activity.id, activity.status_id,
610 activityTarget.contact_id as voter_id,
611 activityAssignment.contact_id as interviewer_id,
612 activity.result as result,
613 activity.activity_date_time as activity_date_time,
614 contact_a.display_name as voter_name";
617 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
618 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
619 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
623 FROM civicrm_activity activity
624 INNER JOIN civicrm_activity_contact activityTarget
625 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
626 INNER JOIN civicrm_activity_contact activityAssignment
627 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
628 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
629 WHERE activity.source_record_id = %1
630 AND activity.activity_type_id = %2
631 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
635 1 => [$surveyId, 'Integer'],
636 2 => [$actTypeId, 'Integer'],
640 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
641 return ($dbCount) ?
$dbCount : 0;
644 $activity = CRM_Core_DAO
::executeQuery($query, $params);
646 while ($activity->fetch()) {
647 $activities[$activity->id
] = [
648 'id' => $activity->id
,
649 'voter_id' => $activity->voter_id
,
650 'voter_name' => $activity->voter_name
,
651 'status_id' => $activity->status_id
,
652 'interviewer_id' => $activity->interviewer_id
,
653 'result' => $activity->result
,
654 'activity_date_time' => $activity->activity_date_time
,
662 * Retrieve survey voter information.
664 * @param int $surveyId
666 * @param int $interviewerId
668 * @param array $statusIds
672 * Survey related contact ids.
674 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
680 $cacheKey = $surveyId;
681 if ($interviewerId) {
682 $cacheKey .= "_{$interviewerId}";
684 if (is_array($statusIds) && !empty($statusIds)) {
685 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
688 static $contactIds = [];
689 if (!isset($contactIds[$cacheKey])) {
690 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
691 foreach ($activities as $values) {
692 $voterIds[$values['voter_id']] = $values;
694 $contactIds[$cacheKey] = $voterIds;
697 return $contactIds[$cacheKey];
701 * This function retrieve all option groups which are created as a result set.
703 * @param string $valueColumnName
705 * an array of option groups.
707 public static function getResultSets($valueColumnName = 'title') {
709 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
711 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
712 $dao = CRM_Core_DAO
::executeQuery($query);
713 while ($dao->fetch()) {
714 $resultSets[$dao->id
] = $dao->$valueColumnName;
721 * check survey activity.
723 * @param int $activityId
727 public static function isSurveyActivity($activityId) {
728 $isSurveyActivity = FALSE;
730 return $isSurveyActivity;
733 $activity = new CRM_Activity_DAO_Activity();
734 $activity->id
= $activityId;
735 $activity->selectAdd('source_record_id, activity_type_id');
736 if ($activity->find(TRUE) &&
737 $activity->source_record_id
739 $surveyActTypes = self
::getSurveyActivityType();
740 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
741 $isSurveyActivity = TRUE;
745 return $isSurveyActivity;
749 * This function retrive all response options of survey.
751 * @param int $surveyId
754 * an array of option values
756 public static function getResponsesOptions($surveyId) {
757 $responseOptions = [];
759 return $responseOptions;
762 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
764 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
767 return $responseOptions;
771 * This function return all voter links with respecting permissions.
773 * @param int $surveyId
774 * @param bool $enclosedInUL
775 * @param string $extraULName
776 * @return array|string
777 * $url array of permissioned links
779 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
785 static $voterLinks = [];
786 if (empty($voterLinks)) {
787 $permissioned = FALSE;
788 if (CRM_Core_Permission
::check('manage campaign') ||
789 CRM_Core_Permission
::check('administer CiviCampaign')
791 $permissioned = TRUE;
794 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
795 $voterLinks['reserve'] = [
797 'url' => 'civicrm/survey/search',
798 'qs' => 'sid=%%id%%&reset=1&op=reserve',
799 'title' => ts('Reserve Respondents'),
802 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
803 $voterLinks['release'] = [
804 'name' => 'interview',
805 'url' => 'civicrm/survey/search',
806 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
807 'title' => ts('Interview Respondents'),
810 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
811 $voterLinks['interview'] = [
813 'url' => 'civicrm/survey/search',
814 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
815 'title' => ts('Release Respondents'),
820 if (CRM_Core_Permission
::check('access CiviReport')) {
821 $reportID = self
::getReportID($surveyId);
823 $voterLinks['report'] = [
825 'url' => "civicrm/report/instance/{$reportID}",
827 'title' => ts('View Survey Report'),
832 $ids = ['id' => $surveyId];
833 foreach ($voterLinks as $link) {
834 if (!empty($link['qs']) &&
835 !CRM_Utils_System
::isNull($link['qs'])
837 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
838 CRM_Core_Action
::replace($link['qs'], $ids)
840 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
842 CRM_Utils_Array
::value('title', $link),
848 $extraLinksName = strtolower($extraULName);
850 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
851 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
852 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
859 * Retrieve survey associated profile id.
861 * @param int $surveyId
865 public static function getSurveyProfileId($surveyId) {
871 if (!array_key_exists($surveyId, $ufIds)) {
872 //get the profile id.
874 'entity_id' => $surveyId,
875 'entity_table' => 'civicrm_survey',
876 'module' => 'CiviCampaign',
879 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
882 $ufIds[$surveyId] = [$first];
885 $ufIds[$surveyId][] = array_shift($second);
889 return $ufIds[$surveyId] ??
NULL;
893 * @param int $surveyId
897 public static function getReportID($surveyId) {
898 static $reportIds = [];
900 if (!array_key_exists($surveyId, $reportIds)) {
901 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
902 $reportID = CRM_Core_DAO
::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
903 $reportIds[$surveyId] = $reportID;
905 return $reportIds[$surveyId];
909 * Decides the contact type for given survey.
911 * @param int $surveyId
913 * @return null|string
915 public static function getSurveyContactType($surveyId) {
918 //apply filter of profile type on search.
919 $profileId = self
::getSurveyProfileId($surveyId);
921 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
922 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
923 $contactType = $profileType;
931 * Get survey supportable profile types.
933 public static function surveyProfileTypes() {
934 static $profileTypes;
936 if (!isset($profileTypes)) {
937 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType
::basicTypes());
938 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
941 return $profileTypes;
945 * Get the valid survey response fields those.
946 * are configured with profile and custom fields.
948 * @param int $surveyId
950 * @param int $surveyTypeId
951 * Survey activity type id.
954 * an array of valid survey response fields.
956 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
957 if (empty($surveyId)) {
961 static $responseFields;
962 $cacheKey = "{$surveyId}_{$surveyTypeId}";
964 if (isset($responseFields[$cacheKey])) {
965 return $responseFields[$cacheKey];
968 $responseFields[$cacheKey] = [];
970 $profileId = self
::getSurveyProfileId($surveyId);
973 return $responseFields;
976 if (!$surveyTypeId) {
977 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
980 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
981 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
984 //don't load these fields in grid.
985 $removeFields = ['File', 'RichTextEditor'];
987 $supportableFieldTypes = self
::surveyProfileTypes();
989 // get custom fields of type survey
990 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
992 foreach ($profileFields as $name => $field) {
993 //get only contact and activity fields.
994 //later stage we might going to consider contact type also.
995 if (in_array($field['field_type'], $supportableFieldTypes)) {
996 // we should allow all supported custom data for survey
997 // In case of activity, allow normal activity and with subtype survey,
998 // suppress custom data of other activity types
999 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1000 if (!in_array($field['html_type'], $removeFields)) {
1001 if ($field['field_type'] != 'Activity') {
1002 $responseFields[$cacheKey][$name] = $field;
1004 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1005 $responseFields[$cacheKey][$name] = $field;
1010 $responseFields[$cacheKey][$name] = $field;
1015 return $responseFields[$cacheKey];
1019 * Get all interviewers of surveys.
1022 * an array of valid survey response fields.
1024 public static function getInterviewers() {
1025 static $interviewers;
1027 if (isset($interviewers)) {
1028 return $interviewers;
1031 $whereClause = NULL;
1032 $activityTypes = self
::getSurveyActivityType();
1033 if (!empty($activityTypes)) {
1034 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1038 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1039 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1042 SELECT contact.id as id,
1043 contact.sort_name as sort_name
1044 FROM civicrm_contact contact
1045 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1046 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1047 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1050 $interviewer = CRM_Core_DAO
::executeQuery($query);
1051 while ($interviewer->fetch()) {
1052 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1055 return $interviewers;
1059 * Check and update the survey respondents.
1061 * @param array $params
1066 public static function releaseRespondent($params) {
1067 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1068 $reserveStatusId = array_search('Scheduled', $activityStatus);
1069 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1070 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1071 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1074 //retrieve all survey activities related to reserve action.
1076 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1078 SELECT activity.id as id,
1079 activity.activity_date_time as activity_date_time,
1080 survey.id as surveyId,
1081 survey.release_frequency as release_frequency
1082 FROM civicrm_activity activity
1083 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1084 WHERE activity.is_deleted = 0
1085 AND activity.status_id = %1
1086 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1087 $activity = CRM_Core_DAO
::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1089 while ($activity->fetch()) {
1090 if (!$activity->release_frequency
) {
1093 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1094 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1095 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1096 if ($totalReservedSeconds < time()) {
1097 $releasedIds[$activity->id
] = $activity->id
;
1101 //released respondent.
1102 if (!empty($releasedIds)) {
1104 UPDATE civicrm_activity
1106 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1107 CRM_Core_DAO
::executeQuery($query);
1108 $releasedCount = count($releasedIds);
1114 'messages' => "Number of respondents released = {$releasedCount}",
1121 * Get options for a given field.
1122 * @see CRM_Core_DAO::buildOptions
1124 * @param string $fieldName
1125 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1126 * @param array $props : whatever is known about this dao object
1128 * @return array|bool
1130 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1132 // Special logic for fields whose options depend on context or properties
1133 switch ($fieldName) {
1134 case 'activity_type_id':
1135 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1136 if ($campaignCompId) {
1137 $params['condition'] = ["component_id={$campaignCompId}"];
1141 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);