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 (empty($params['id'])) {
66 if (empty($params['created_id'])) {
67 $params['created_id'] = CRM_Core_Session
::getLoggedInContactID();
70 if (empty($params['created_date'])) {
71 $params['created_date'] = date('YmdHis');
75 $dao = self
::writeRecord($params);
77 if (!empty($params['custom']) && is_array($params['custom'])) {
78 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
84 * Retrieve surveys for dashboard.
86 * @param array $params
87 * @param bool $onlyCount
91 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
92 //build the limit and order clause.
93 $limitClause = $orderByClause = $lookupTableJoins = NULL;
96 'sort' => 'created_date',
99 'sortOrder' => 'desc',
101 foreach ($sortParams as $name => $default) {
102 if (!empty($params[$name])) {
103 $sortParams[$name] = $params[$name];
107 //need to lookup tables.
108 $orderOnSurveyTable = TRUE;
109 if ($sortParams['sort'] == 'campaign') {
110 $orderOnSurveyTable = FALSE;
111 $lookupTableJoins = '
112 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
113 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
115 elseif ($sortParams['sort'] == 'activity_type') {
116 $orderOnSurveyTable = FALSE;
117 $lookupTableJoins = "
118 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
119 OR survey.activity_type_id IS NULL )
120 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
121 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
123 elseif ($sortParams['sort'] == 'isActive') {
124 $sortParams['sort'] = 'is_active';
126 if ($orderOnSurveyTable) {
127 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
129 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
132 //build the where clause.
133 $queryParams = $where = [];
135 //we only have activity type as a
136 //difference between survey and petition.
137 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
138 if ($petitionTypeID) {
139 $where[] = "( survey.activity_type_id != %1 )";
140 $queryParams[1] = [$petitionTypeID, 'Positive'];
143 if (!empty($params['title'])) {
144 $where[] = "( survey.title LIKE %2 )";
145 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
147 if (!empty($params['campaign_id'])) {
148 $where[] = '( survey.campaign_id = %3 )';
149 $queryParams[3] = [$params['campaign_id'], 'Positive'];
151 if (!empty($params['activity_type_id'])) {
152 $typeId = $params['activity_type_id'];
153 if (is_array($params['activity_type_id'])) {
154 $typeId = implode(' , ', $params['activity_type_id']);
156 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
159 if (!empty($where)) {
160 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
164 SELECT survey.id as id,
165 survey.title as title,
166 survey.is_active as is_active,
167 survey.result_id as result_id,
168 survey.is_default as is_default,
169 survey.campaign_id as campaign_id,
170 survey.activity_type_id as activity_type_id,
171 survey.release_frequency as release_frequency,
172 survey.max_number_of_contacts as max_number_of_contacts,
173 survey.default_number_of_contacts as default_number_of_contacts';
175 $selectClause = 'SELECT COUNT(*)';
177 $fromClause = 'FROM civicrm_survey survey';
179 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
183 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
196 'max_number_of_contacts',
197 'default_number_of_contacts',
200 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
201 while ($survey->fetch()) {
202 foreach ($properties as $property) {
203 $surveys[$survey->id
][$property] = $survey->$property;
211 * Get the survey count.
214 public static function getSurveyCount() {
215 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
221 * @param bool $onlyActive
222 * Retrieve only active surveys.
223 * @param bool $onlyDefault
224 * Retrieve only default survey.
225 * @param bool $forceAll
226 * Retrieve all surveys.
227 * @param bool $includePetition
228 * Include or exclude petitions.
231 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
233 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
234 foreach ($cacheKeyParams as $param) {
235 $cacheParam = $
$param;
239 $cacheKey .= '_' . $cacheParam;
244 if (!isset($surveys[$cacheKey])) {
245 if (!$includePetition) {
246 //we only have activity type as a
247 //difference between survey and petition.
248 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'petition');
251 if ($petitionTypeID) {
252 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
255 if (!$forceAll && $onlyActive) {
256 $where[] = '( survey.is_active = 1 )';
258 if (!$forceAll && $onlyDefault) {
259 $where[] = '( survey.is_default = 1 )';
261 $whereClause = implode(' AND ', $where);
264 SELECT survey.id as id,
265 survey.title as title
266 FROM civicrm_survey as survey
267 WHERE {$whereClause}";
268 $surveys[$cacheKey] = [];
269 $survey = CRM_Core_DAO
::executeQuery($query);
270 while ($survey->fetch()) {
271 $surveys[$cacheKey][$survey->id
] = $survey->title
;
275 return $surveys[$cacheKey];
279 * Get Survey activity types.
281 * @param string $returnColumn
282 * @param bool $includePetitionActivityType
286 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
287 static $activityTypes;
288 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
290 if (!isset($activityTypes[$cacheKey])) {
292 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
293 if ($campaignCompId) {
294 $condition = " AND v.component_id={$campaignCompId}";
295 if (!$includePetitionActivityType) {
296 $condition .= " AND v.name != 'Petition'";
298 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
305 if (!empty($activityTypes[$cacheKey])) {
306 return $activityTypes[$cacheKey];
314 * Get Surveys custom groups.
316 * @param array $surveyTypes
317 * an array of survey type id.
321 public static function getSurveyCustomGroups($surveyTypes = []) {
323 if (!is_array($surveyTypes)) {
324 $surveyTypes = [$surveyTypes];
327 if (!empty($surveyTypes)) {
328 $activityTypes = array_flip($surveyTypes);
331 $activityTypes = self
::getSurveyActivityType();
334 if (!empty($activityTypes)) {
335 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
337 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
338 FROM civicrm_custom_group cg
339 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
341 $dao = CRM_Core_DAO
::executeQuery($query);
342 while ($dao->fetch()) {
343 $customGroups[$dao->id
]['id'] = $dao->id
;
344 $customGroups[$dao->id
]['name'] = $dao->name
;
345 $customGroups[$dao->id
]['title'] = $dao->title
;
346 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
350 return $customGroups;
354 * Update the is_active flag in the db.
357 * Id of the database record.
358 * @param bool $is_active
359 * Value we want to set the is_active field.
362 * true if we found and updated the object, else false
364 public static function setIsActive($id, $is_active) {
365 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
376 public static function del($id) {
380 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
382 CRM_Report_BAO_ReportInstance
::del($reportId);
384 $dao = new CRM_Campaign_DAO_Survey();
386 return $dao->delete();
390 * This function retrieve contact information.
392 * @param array $voterIds
393 * @param array $returnProperties
394 * An array of return elements.
397 * array of contact info.
399 public static function voterDetails($voterIds, $returnProperties = []) {
401 if (!is_array($voterIds) ||
empty($voterIds)) {
402 return $voterDetails;
405 if (empty($returnProperties)) {
406 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
407 'contact_autocomplete_options'
409 $returnProperties = array_fill_keys(array_merge(
410 ['contact_type', 'contact_sub_type', 'sort_name'],
411 array_keys($autocompleteContactSearch)
415 $select = $from = [];
416 foreach ($returnProperties as $property => $ignore) {
417 $value = (in_array($property, [
420 ])) ?
'address' : $property;
424 case 'contact_sub_type':
425 $select[] = "$property as $property";
426 $from['contact'] = 'civicrm_contact contact';
432 case 'street_address':
433 $select[] = "$property as $property";
434 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
438 case 'state_province':
439 $select[] = "{$property}.name as $property";
440 if (!in_array('address', $from)) {
441 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
443 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
448 //finally retrieve contact details.
449 if (!empty($select) && !empty($from)) {
450 $fromClause = implode(' ', $from);
451 $selectClause = implode(', ', $select);
452 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
455 SELECT contact.id as contactId, $selectClause
459 $contact = CRM_Core_DAO
::executeQuery($query);
460 while ($contact->fetch()) {
461 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
462 foreach ($returnProperties as $property => $ignore) {
463 $voterDetails[$contact->contactId
][$property] = $contact->$property;
465 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
469 $voterDetails[$contact->contactId
]['contact_type'] = $image;
473 return $voterDetails;
477 * This function retrieve survey related activities w/ for give voter ids.
479 * @param int $surveyId
481 * @param array $voterIds
484 * @param int $interviewerId
485 * @param array $statusIds
488 * array of survey activity.
490 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
491 $activityDetails = [];
493 !is_array($voterIds) ||
empty($voterIds)
495 return $activityDetails;
499 if (is_array($statusIds) && !empty($statusIds)) {
500 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
503 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
504 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
505 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
506 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
508 $params[1] = [$surveyId, 'Integer'];
510 SELECT activity.id, activity.status_id,
511 activityTarget.contact_id as voter_id,
512 activityAssignment.contact_id as interviewer_id
513 FROM civicrm_activity activity
514 INNER JOIN civicrm_activity_contact activityTarget
515 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
516 INNER JOIN civicrm_activity_contact activityAssignment
517 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
518 WHERE activity.source_record_id = %1
519 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
520 if (!empty($interviewerId)) {
521 $query .= "AND activityAssignment.contact_id = %2 ";
522 $params[2] = [$interviewerId, 'Integer'];
524 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
526 $activity = CRM_Core_DAO
::executeQuery($query, $params);
527 while ($activity->fetch()) {
528 $activityDetails[$activity->voter_id
] = [
529 'voter_id' => $activity->voter_id
,
530 'status_id' => $activity->status_id
,
531 'activity_id' => $activity->id
,
532 'interviewer_id' => $activity->interviewer_id
,
536 return $activityDetails;
540 * This function retrieve survey related activities.
542 * @param int $surveyId
543 * @param int $interviewerId
544 * @param array $statusIds
545 * @param array $voterIds
546 * @param bool $onlyCount
549 * An array of survey activity.
551 public static function getSurveyActivities(
553 $interviewerId = NULL,
559 $surveyActivityCount = 0;
561 return ($onlyCount) ?
0 : $activities;
565 if (!empty($statusIds)) {
566 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
569 if ($interviewerId) {
570 $where[] = "( activityAssignment.contact_id = $interviewerId )";
573 if (!empty($voterIds)) {
574 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
578 if (!empty($where)) {
579 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
582 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
588 $select = "SELECT count(activity.id)";
592 SELECT activity.id, activity.status_id,
593 activityTarget.contact_id as voter_id,
594 activityAssignment.contact_id as interviewer_id,
595 activity.result as result,
596 activity.activity_date_time as activity_date_time,
597 contact_a.display_name as voter_name";
600 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
601 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
602 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
606 FROM civicrm_activity activity
607 INNER JOIN civicrm_activity_contact activityTarget
608 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
609 INNER JOIN civicrm_activity_contact activityAssignment
610 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
611 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
612 WHERE activity.source_record_id = %1
613 AND activity.activity_type_id = %2
614 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
618 1 => [$surveyId, 'Integer'],
619 2 => [$actTypeId, 'Integer'],
623 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
624 return ($dbCount) ?
$dbCount : 0;
627 $activity = CRM_Core_DAO
::executeQuery($query, $params);
629 while ($activity->fetch()) {
630 $activities[$activity->id
] = [
631 'id' => $activity->id
,
632 'voter_id' => $activity->voter_id
,
633 'voter_name' => $activity->voter_name
,
634 'status_id' => $activity->status_id
,
635 'interviewer_id' => $activity->interviewer_id
,
636 'result' => $activity->result
,
637 'activity_date_time' => $activity->activity_date_time
,
645 * Retrieve survey voter information.
647 * @param int $surveyId
649 * @param int $interviewerId
651 * @param array $statusIds
655 * Survey related contact ids.
657 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
663 $cacheKey = $surveyId;
664 if ($interviewerId) {
665 $cacheKey .= "_{$interviewerId}";
667 if (is_array($statusIds) && !empty($statusIds)) {
668 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
671 static $contactIds = [];
672 if (!isset($contactIds[$cacheKey])) {
673 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
674 foreach ($activities as $values) {
675 $voterIds[$values['voter_id']] = $values;
677 $contactIds[$cacheKey] = $voterIds;
680 return $contactIds[$cacheKey];
684 * This function retrieve all option groups which are created as a result set.
686 * @param string $valueColumnName
688 * an array of option groups.
690 public static function getResultSets($valueColumnName = 'title') {
692 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
694 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
695 $dao = CRM_Core_DAO
::executeQuery($query);
696 while ($dao->fetch()) {
697 $resultSets[$dao->id
] = $dao->$valueColumnName;
704 * check survey activity.
706 * @param int $activityId
710 public static function isSurveyActivity($activityId) {
711 $isSurveyActivity = FALSE;
713 return $isSurveyActivity;
716 $activity = new CRM_Activity_DAO_Activity();
717 $activity->id
= $activityId;
718 $activity->selectAdd('source_record_id, activity_type_id');
719 if ($activity->find(TRUE) &&
720 $activity->source_record_id
722 $surveyActTypes = self
::getSurveyActivityType();
723 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
724 $isSurveyActivity = TRUE;
728 return $isSurveyActivity;
732 * This function retrive all response options of survey.
734 * @param int $surveyId
737 * an array of option values
739 public static function getResponsesOptions($surveyId) {
740 $responseOptions = [];
742 return $responseOptions;
745 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
747 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
750 return $responseOptions;
754 * This function return all voter links with respecting permissions.
756 * @param int $surveyId
757 * @param bool $enclosedInUL
758 * @param string $extraULName
759 * @return array|string
760 * $url array of permissioned links
762 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
768 static $voterLinks = [];
769 if (empty($voterLinks)) {
770 $permissioned = FALSE;
771 if (CRM_Core_Permission
::check('manage campaign') ||
772 CRM_Core_Permission
::check('administer CiviCampaign')
774 $permissioned = TRUE;
777 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
778 $voterLinks['reserve'] = [
780 'url' => 'civicrm/survey/search',
781 'qs' => 'sid=%%id%%&reset=1&op=reserve',
782 'title' => ts('Reserve Respondents'),
785 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
786 $voterLinks['release'] = [
787 'name' => 'interview',
788 'url' => 'civicrm/survey/search',
789 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
790 'title' => ts('Interview Respondents'),
793 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
794 $voterLinks['interview'] = [
796 'url' => 'civicrm/survey/search',
797 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
798 'title' => ts('Release Respondents'),
803 if (CRM_Core_Permission
::check('access CiviReport')) {
804 $reportID = self
::getReportID($surveyId);
806 $voterLinks['report'] = [
808 'url' => "civicrm/report/instance/{$reportID}",
810 'title' => ts('View Survey Report'),
815 $ids = ['id' => $surveyId];
816 foreach ($voterLinks as $link) {
817 if (!empty($link['qs']) &&
818 !CRM_Utils_System
::isNull($link['qs'])
820 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
821 CRM_Core_Action
::replace($link['qs'], $ids)
823 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
825 CRM_Utils_Array
::value('title', $link),
831 $extraLinksName = strtolower($extraULName);
833 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
834 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
835 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
842 * Retrieve survey associated profile id.
844 * @param int $surveyId
848 public static function getSurveyProfileId($surveyId) {
854 if (!array_key_exists($surveyId, $ufIds)) {
855 //get the profile id.
857 'entity_id' => $surveyId,
858 'entity_table' => 'civicrm_survey',
859 'module' => 'CiviCampaign',
862 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
865 $ufIds[$surveyId] = [$first];
868 $ufIds[$surveyId][] = array_shift($second);
872 return $ufIds[$surveyId] ??
NULL;
876 * @param int $surveyId
880 public static function getReportID($surveyId) {
881 static $reportIds = [];
883 if (!array_key_exists($surveyId, $reportIds)) {
884 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
885 $reportID = CRM_Core_DAO
::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
886 $reportIds[$surveyId] = $reportID;
888 return $reportIds[$surveyId];
892 * Decides the contact type for given survey.
894 * @param int $surveyId
896 * @return null|string
898 public static function getSurveyContactType($surveyId) {
901 //apply filter of profile type on search.
902 $profileId = self
::getSurveyProfileId($surveyId);
904 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
905 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
906 $contactType = $profileType;
914 * Get survey supportable profile types.
916 public static function surveyProfileTypes() {
917 static $profileTypes;
919 if (!isset($profileTypes)) {
920 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType
::basicTypes());
921 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
924 return $profileTypes;
928 * Get the valid survey response fields those.
929 * are configured with profile and custom fields.
931 * @param int $surveyId
933 * @param int $surveyTypeId
934 * Survey activity type id.
937 * an array of valid survey response fields.
939 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
940 if (empty($surveyId)) {
944 static $responseFields;
945 $cacheKey = "{$surveyId}_{$surveyTypeId}";
947 if (isset($responseFields[$cacheKey])) {
948 return $responseFields[$cacheKey];
951 $responseFields[$cacheKey] = [];
953 $profileId = self
::getSurveyProfileId($surveyId);
956 return $responseFields;
959 if (!$surveyTypeId) {
960 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
963 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
964 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
967 //don't load these fields in grid.
968 $removeFields = ['File', 'RichTextEditor'];
970 $supportableFieldTypes = self
::surveyProfileTypes();
972 // get custom fields of type survey
973 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
975 foreach ($profileFields as $name => $field) {
976 //get only contact and activity fields.
977 //later stage we might going to consider contact type also.
978 if (in_array($field['field_type'], $supportableFieldTypes)) {
979 // we should allow all supported custom data for survey
980 // In case of activity, allow normal activity and with subtype survey,
981 // suppress custom data of other activity types
982 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
983 if (!in_array($field['html_type'], $removeFields)) {
984 if ($field['field_type'] != 'Activity') {
985 $responseFields[$cacheKey][$name] = $field;
987 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
988 $responseFields[$cacheKey][$name] = $field;
993 $responseFields[$cacheKey][$name] = $field;
998 return $responseFields[$cacheKey];
1002 * Get all interviewers of surveys.
1005 * an array of valid survey response fields.
1007 public static function getInterviewers() {
1008 static $interviewers;
1010 if (isset($interviewers)) {
1011 return $interviewers;
1014 $whereClause = NULL;
1015 $activityTypes = self
::getSurveyActivityType();
1016 if (!empty($activityTypes)) {
1017 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1021 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1022 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1025 SELECT contact.id as id,
1026 contact.sort_name as sort_name
1027 FROM civicrm_contact contact
1028 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1029 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1030 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1033 $interviewer = CRM_Core_DAO
::executeQuery($query);
1034 while ($interviewer->fetch()) {
1035 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1038 return $interviewers;
1042 * Check and update the survey respondents.
1044 * @param array $params
1049 public static function releaseRespondent($params) {
1050 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1051 $reserveStatusId = array_search('Scheduled', $activityStatus);
1052 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1053 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1054 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1057 //retrieve all survey activities related to reserve action.
1059 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1061 SELECT activity.id as id,
1062 activity.activity_date_time as activity_date_time,
1063 survey.id as surveyId,
1064 survey.release_frequency as release_frequency
1065 FROM civicrm_activity activity
1066 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1067 WHERE activity.is_deleted = 0
1068 AND activity.status_id = %1
1069 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1070 $activity = CRM_Core_DAO
::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1072 while ($activity->fetch()) {
1073 if (!$activity->release_frequency
) {
1076 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1077 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1078 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1079 if ($totalReservedSeconds < time()) {
1080 $releasedIds[$activity->id
] = $activity->id
;
1084 //released respondent.
1085 if (!empty($releasedIds)) {
1087 UPDATE civicrm_activity
1089 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1090 CRM_Core_DAO
::executeQuery($query);
1091 $releasedCount = count($releasedIds);
1097 'messages' => "Number of respondents released = {$releasedCount}",
1104 * Get options for a given field.
1105 * @see CRM_Core_DAO::buildOptions
1107 * @param string $fieldName
1108 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1109 * @param array $props : whatever is known about this dao object
1111 * @return array|bool
1113 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1115 // Special logic for fields whose options depend on context or properties
1116 switch ($fieldName) {
1117 case 'activity_type_id':
1118 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1119 if ($campaignCompId) {
1120 $params['condition'] = ["component_id={$campaignCompId}"];
1124 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);