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
implements Civi\Test\HookInterface
{
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);
375 public static function del($id) {
379 self
::deleteRecord(['id' => $id]);
384 * Event fired prior to modifying a Survey.
385 * @param \Civi\Core\Event\PreEvent $event
387 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
388 if ($event->action
=== 'delete' && $event->id
) {
389 $reportId = self
::getReportID($event->id
);
391 CRM_Report_BAO_ReportInstance
::deleteRecord(['id' => $reportId]);
397 * This function retrieve contact information.
399 * @param array $voterIds
400 * @param array $returnProperties
401 * An array of return elements.
404 * array of contact info.
406 public static function voterDetails($voterIds, $returnProperties = []) {
408 if (!is_array($voterIds) ||
empty($voterIds)) {
409 return $voterDetails;
412 if (empty($returnProperties)) {
413 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
414 'contact_autocomplete_options'
416 $returnProperties = array_fill_keys(array_merge(
417 ['contact_type', 'contact_sub_type', 'sort_name'],
418 array_keys($autocompleteContactSearch)
422 $select = $from = [];
423 foreach ($returnProperties as $property => $ignore) {
424 $value = (in_array($property, [
427 ])) ?
'address' : $property;
431 case 'contact_sub_type':
432 $select[] = "$property as $property";
433 $from['contact'] = 'civicrm_contact contact';
439 case 'street_address':
440 $select[] = "$property as $property";
441 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
445 case 'state_province':
446 $select[] = "{$property}.name as $property";
447 if (!in_array('address', $from)) {
448 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
450 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
455 //finally retrieve contact details.
456 if (!empty($select) && !empty($from)) {
457 $fromClause = implode(' ', $from);
458 $selectClause = implode(', ', $select);
459 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
462 SELECT contact.id as contactId, $selectClause
466 $contact = CRM_Core_DAO
::executeQuery($query);
467 while ($contact->fetch()) {
468 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
469 foreach ($returnProperties as $property => $ignore) {
470 $voterDetails[$contact->contactId
][$property] = $contact->$property;
472 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
476 $voterDetails[$contact->contactId
]['contact_type'] = $image;
480 return $voterDetails;
484 * This function retrieve survey related activities w/ for give voter ids.
486 * @param int $surveyId
488 * @param array $voterIds
491 * @param int $interviewerId
492 * @param array $statusIds
495 * array of survey activity.
497 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
498 $activityDetails = [];
500 !is_array($voterIds) ||
empty($voterIds)
502 return $activityDetails;
506 if (is_array($statusIds) && !empty($statusIds)) {
507 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
510 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
511 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
512 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
513 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
515 $params[1] = [$surveyId, 'Integer'];
517 SELECT activity.id, activity.status_id,
518 activityTarget.contact_id as voter_id,
519 activityAssignment.contact_id as interviewer_id
520 FROM civicrm_activity activity
521 INNER JOIN civicrm_activity_contact activityTarget
522 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
523 INNER JOIN civicrm_activity_contact activityAssignment
524 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
525 WHERE activity.source_record_id = %1
526 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
527 if (!empty($interviewerId)) {
528 $query .= "AND activityAssignment.contact_id = %2 ";
529 $params[2] = [$interviewerId, 'Integer'];
531 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
533 $activity = CRM_Core_DAO
::executeQuery($query, $params);
534 while ($activity->fetch()) {
535 $activityDetails[$activity->voter_id
] = [
536 'voter_id' => $activity->voter_id
,
537 'status_id' => $activity->status_id
,
538 'activity_id' => $activity->id
,
539 'interviewer_id' => $activity->interviewer_id
,
543 return $activityDetails;
547 * This function retrieve survey related activities.
549 * @param int $surveyId
550 * @param int $interviewerId
551 * @param array $statusIds
552 * @param array $voterIds
553 * @param bool $onlyCount
556 * An array of survey activity.
558 public static function getSurveyActivities(
560 $interviewerId = NULL,
566 $surveyActivityCount = 0;
568 return ($onlyCount) ?
0 : $activities;
572 if (!empty($statusIds)) {
573 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
576 if ($interviewerId) {
577 $where[] = "( activityAssignment.contact_id = $interviewerId )";
580 if (!empty($voterIds)) {
581 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
585 if (!empty($where)) {
586 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
589 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
595 $select = "SELECT count(activity.id)";
599 SELECT activity.id, activity.status_id,
600 activityTarget.contact_id as voter_id,
601 activityAssignment.contact_id as interviewer_id,
602 activity.result as result,
603 activity.activity_date_time as activity_date_time,
604 contact_a.display_name as voter_name";
607 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
608 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
609 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
613 FROM civicrm_activity activity
614 INNER JOIN civicrm_activity_contact activityTarget
615 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
616 INNER JOIN civicrm_activity_contact activityAssignment
617 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
618 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
619 WHERE activity.source_record_id = %1
620 AND activity.activity_type_id = %2
621 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
625 1 => [$surveyId, 'Integer'],
626 2 => [$actTypeId, 'Integer'],
630 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
631 return ($dbCount) ?
$dbCount : 0;
634 $activity = CRM_Core_DAO
::executeQuery($query, $params);
636 while ($activity->fetch()) {
637 $activities[$activity->id
] = [
638 'id' => $activity->id
,
639 'voter_id' => $activity->voter_id
,
640 'voter_name' => $activity->voter_name
,
641 'status_id' => $activity->status_id
,
642 'interviewer_id' => $activity->interviewer_id
,
643 'result' => $activity->result
,
644 'activity_date_time' => $activity->activity_date_time
,
652 * Retrieve survey voter information.
654 * @param int $surveyId
656 * @param int $interviewerId
658 * @param array $statusIds
662 * Survey related contact ids.
664 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
670 $cacheKey = $surveyId;
671 if ($interviewerId) {
672 $cacheKey .= "_{$interviewerId}";
674 if (is_array($statusIds) && !empty($statusIds)) {
675 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
678 static $contactIds = [];
679 if (!isset($contactIds[$cacheKey])) {
680 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
681 foreach ($activities as $values) {
682 $voterIds[$values['voter_id']] = $values;
684 $contactIds[$cacheKey] = $voterIds;
687 return $contactIds[$cacheKey];
691 * This function retrieve all option groups which are created as a result set.
693 * @param string $valueColumnName
695 * an array of option groups.
697 public static function getResultSets($valueColumnName = 'title') {
699 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
701 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
702 $dao = CRM_Core_DAO
::executeQuery($query);
703 while ($dao->fetch()) {
704 $resultSets[$dao->id
] = $dao->$valueColumnName;
711 * check survey activity.
713 * @param int $activityId
717 public static function isSurveyActivity($activityId) {
718 $isSurveyActivity = FALSE;
720 return $isSurveyActivity;
723 $activity = new CRM_Activity_DAO_Activity();
724 $activity->id
= $activityId;
725 $activity->selectAdd('source_record_id, activity_type_id');
726 if ($activity->find(TRUE) &&
727 $activity->source_record_id
729 $surveyActTypes = self
::getSurveyActivityType();
730 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
731 $isSurveyActivity = TRUE;
735 return $isSurveyActivity;
739 * This function retrive all response options of survey.
741 * @param int $surveyId
744 * an array of option values
746 public static function getResponsesOptions($surveyId) {
747 $responseOptions = [];
749 return $responseOptions;
752 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
754 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
757 return $responseOptions;
761 * This function return all voter links with respecting permissions.
763 * @param int $surveyId
764 * @param bool $enclosedInUL
765 * @param string $extraULName
766 * @return array|string
767 * $url array of permissioned links
769 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
775 static $voterLinks = [];
776 if (empty($voterLinks)) {
777 $permissioned = FALSE;
778 if (CRM_Core_Permission
::check('manage campaign') ||
779 CRM_Core_Permission
::check('administer CiviCampaign')
781 $permissioned = TRUE;
784 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
785 $voterLinks['reserve'] = [
787 'url' => 'civicrm/survey/search',
788 'qs' => 'sid=%%id%%&reset=1&op=reserve',
789 'title' => ts('Reserve Respondents'),
792 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
793 $voterLinks['release'] = [
794 'name' => 'interview',
795 'url' => 'civicrm/survey/search',
796 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
797 'title' => ts('Interview Respondents'),
800 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
801 $voterLinks['interview'] = [
803 'url' => 'civicrm/survey/search',
804 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
805 'title' => ts('Release Respondents'),
810 if (CRM_Core_Permission
::check('access CiviReport')) {
811 $reportID = self
::getReportID($surveyId);
813 $voterLinks['report'] = [
815 'url' => "civicrm/report/instance/{$reportID}",
817 'title' => ts('View Survey Report'),
822 $ids = ['id' => $surveyId];
823 foreach ($voterLinks as $link) {
824 if (!empty($link['qs']) &&
825 !CRM_Utils_System
::isNull($link['qs'])
827 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
828 CRM_Core_Action
::replace($link['qs'], $ids)
830 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
832 CRM_Utils_Array
::value('title', $link),
838 $extraLinksName = strtolower($extraULName);
840 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
841 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
842 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
849 * Retrieve survey associated profile id.
851 * @param int $surveyId
855 public static function getSurveyProfileId($surveyId) {
861 if (!array_key_exists($surveyId, $ufIds)) {
862 //get the profile id.
864 'entity_id' => $surveyId,
865 'entity_table' => 'civicrm_survey',
866 'module' => 'CiviCampaign',
869 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
872 $ufIds[$surveyId] = [$first];
875 $ufIds[$surveyId][] = array_shift($second);
879 return $ufIds[$surveyId] ??
NULL;
883 * @param int $surveyId
887 public static function getReportID($surveyId) {
888 static $reportIds = [];
890 if (!array_key_exists($surveyId, $reportIds)) {
891 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
892 $reportID = CRM_Core_DAO
::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
893 $reportIds[$surveyId] = $reportID;
895 return $reportIds[$surveyId];
899 * Decides the contact type for given survey.
901 * @param int $surveyId
903 * @return null|string
905 public static function getSurveyContactType($surveyId) {
908 //apply filter of profile type on search.
909 $profileId = self
::getSurveyProfileId($surveyId);
911 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
912 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
913 $contactType = $profileType;
921 * Get survey supportable profile types.
923 public static function surveyProfileTypes() {
924 static $profileTypes;
926 if (!isset($profileTypes)) {
927 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType
::basicTypes());
928 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
931 return $profileTypes;
935 * Get the valid survey response fields those.
936 * are configured with profile and custom fields.
938 * @param int $surveyId
940 * @param int $surveyTypeId
941 * Survey activity type id.
944 * an array of valid survey response fields.
946 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
947 if (empty($surveyId)) {
951 static $responseFields;
952 $cacheKey = "{$surveyId}_{$surveyTypeId}";
954 if (isset($responseFields[$cacheKey])) {
955 return $responseFields[$cacheKey];
958 $responseFields[$cacheKey] = [];
960 $profileId = self
::getSurveyProfileId($surveyId);
963 return $responseFields;
966 if (!$surveyTypeId) {
967 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
970 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
971 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
974 //don't load these fields in grid.
975 $removeFields = ['File', 'RichTextEditor'];
977 $supportableFieldTypes = self
::surveyProfileTypes();
979 // get custom fields of type survey
980 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
982 foreach ($profileFields as $name => $field) {
983 //get only contact and activity fields.
984 //later stage we might going to consider contact type also.
985 if (in_array($field['field_type'], $supportableFieldTypes)) {
986 // we should allow all supported custom data for survey
987 // In case of activity, allow normal activity and with subtype survey,
988 // suppress custom data of other activity types
989 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
990 if (!in_array($field['html_type'], $removeFields)) {
991 if ($field['field_type'] != 'Activity') {
992 $responseFields[$cacheKey][$name] = $field;
994 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
995 $responseFields[$cacheKey][$name] = $field;
1000 $responseFields[$cacheKey][$name] = $field;
1005 return $responseFields[$cacheKey];
1009 * Get all interviewers of surveys.
1012 * an array of valid survey response fields.
1014 public static function getInterviewers() {
1015 static $interviewers;
1017 if (isset($interviewers)) {
1018 return $interviewers;
1021 $whereClause = NULL;
1022 $activityTypes = self
::getSurveyActivityType();
1023 if (!empty($activityTypes)) {
1024 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1028 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1029 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1032 SELECT contact.id as id,
1033 contact.sort_name as sort_name
1034 FROM civicrm_contact contact
1035 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1036 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1037 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1040 $interviewer = CRM_Core_DAO
::executeQuery($query);
1041 while ($interviewer->fetch()) {
1042 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1045 return $interviewers;
1049 * Check and update the survey respondents.
1051 * @param array $params
1056 public static function releaseRespondent($params) {
1057 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1058 $reserveStatusId = array_search('Scheduled', $activityStatus);
1059 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1060 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1061 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1064 //retrieve all survey activities related to reserve action.
1066 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1068 SELECT activity.id as id,
1069 activity.activity_date_time as activity_date_time,
1070 survey.id as surveyId,
1071 survey.release_frequency as release_frequency
1072 FROM civicrm_activity activity
1073 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1074 WHERE activity.is_deleted = 0
1075 AND activity.status_id = %1
1076 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1077 $activity = CRM_Core_DAO
::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1079 while ($activity->fetch()) {
1080 if (!$activity->release_frequency
) {
1083 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1084 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1085 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1086 if ($totalReservedSeconds < time()) {
1087 $releasedIds[$activity->id
] = $activity->id
;
1091 //released respondent.
1092 if (!empty($releasedIds)) {
1094 UPDATE civicrm_activity
1096 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1097 CRM_Core_DAO
::executeQuery($query);
1098 $releasedCount = count($releasedIds);
1104 'messages' => "Number of respondents released = {$releasedCount}",
1111 * Get options for a given field.
1112 * @see CRM_Core_DAO::buildOptions
1114 * @param string $fieldName
1115 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1116 * @param array $props : whatever is known about this dao object
1118 * @return array|bool
1120 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1122 // Special logic for fields whose options depend on context or properties
1123 switch ($fieldName) {
1124 case 'activity_type_id':
1125 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1126 if ($campaignCompId) {
1127 $params['condition'] = ["component_id={$campaignCompId}"];
1131 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);