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);
81 * Retrieve surveys for dashboard.
83 * @param array $params
84 * @param bool $onlyCount
88 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
89 //build the limit and order clause.
90 $limitClause = $orderByClause = $lookupTableJoins = NULL;
93 'sort' => 'created_date',
96 'sortOrder' => 'desc',
98 foreach ($sortParams as $name => $default) {
99 if (!empty($params[$name])) {
100 $sortParams[$name] = $params[$name];
104 //need to lookup tables.
105 $orderOnSurveyTable = TRUE;
106 if ($sortParams['sort'] == 'campaign') {
107 $orderOnSurveyTable = FALSE;
108 $lookupTableJoins = '
109 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
110 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
112 elseif ($sortParams['sort'] == 'activity_type') {
113 $orderOnSurveyTable = FALSE;
114 $lookupTableJoins = "
115 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
116 OR survey.activity_type_id IS NULL )
117 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
118 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
120 elseif ($sortParams['sort'] == 'isActive') {
121 $sortParams['sort'] = 'is_active';
123 if ($orderOnSurveyTable) {
124 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
126 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
129 //build the where clause.
130 $queryParams = $where = [];
132 //we only have activity type as a
133 //difference between survey and petition.
134 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
135 if ($petitionTypeID) {
136 $where[] = "( survey.activity_type_id != %1 )";
137 $queryParams[1] = [$petitionTypeID, 'Positive'];
140 if (!empty($params['title'])) {
141 $where[] = "( survey.title LIKE %2 )";
142 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
144 if (!empty($params['campaign_id'])) {
145 $where[] = '( survey.campaign_id = %3 )';
146 $queryParams[3] = [$params['campaign_id'], 'Positive'];
148 if (!empty($params['activity_type_id'])) {
149 $typeId = $params['activity_type_id'];
150 if (is_array($params['activity_type_id'])) {
151 $typeId = implode(' , ', $params['activity_type_id']);
153 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
156 if (!empty($where)) {
157 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
161 SELECT survey.id as id,
162 survey.title as title,
163 survey.is_active as is_active,
164 survey.result_id as result_id,
165 survey.is_default as is_default,
166 survey.campaign_id as campaign_id,
167 survey.activity_type_id as activity_type_id,
168 survey.release_frequency as release_frequency,
169 survey.max_number_of_contacts as max_number_of_contacts,
170 survey.default_number_of_contacts as default_number_of_contacts';
172 $selectClause = 'SELECT COUNT(*)';
174 $fromClause = 'FROM civicrm_survey survey';
176 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
180 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
193 'max_number_of_contacts',
194 'default_number_of_contacts',
197 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
198 while ($survey->fetch()) {
199 foreach ($properties as $property) {
200 $surveys[$survey->id
][$property] = $survey->$property;
208 * Get the survey count.
211 public static function getSurveyCount() {
212 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
218 * @param bool $onlyActive
219 * Retrieve only active surveys.
220 * @param bool $onlyDefault
221 * Retrieve only default survey.
222 * @param bool $forceAll
223 * Retrieve all surveys.
224 * @param bool $includePetition
225 * Include or exclude petitions.
228 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
230 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
231 foreach ($cacheKeyParams as $param) {
232 $cacheParam = $
$param;
236 $cacheKey .= '_' . $cacheParam;
241 if (!isset($surveys[$cacheKey])) {
242 if (!$includePetition) {
243 //we only have activity type as a
244 //difference between survey and petition.
245 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'petition');
248 if ($petitionTypeID) {
249 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
252 if (!$forceAll && $onlyActive) {
253 $where[] = '( survey.is_active = 1 )';
255 if (!$forceAll && $onlyDefault) {
256 $where[] = '( survey.is_default = 1 )';
258 $whereClause = implode(' AND ', $where);
261 SELECT survey.id as id,
262 survey.title as title
263 FROM civicrm_survey as survey
264 WHERE {$whereClause}";
265 $surveys[$cacheKey] = [];
266 $survey = CRM_Core_DAO
::executeQuery($query);
267 while ($survey->fetch()) {
268 $surveys[$cacheKey][$survey->id
] = $survey->title
;
272 return $surveys[$cacheKey];
276 * Get Survey activity types.
278 * @param string $returnColumn
279 * @param bool $includePetitionActivityType
283 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
284 static $activityTypes;
285 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
287 if (!isset($activityTypes[$cacheKey])) {
289 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
290 if ($campaignCompId) {
291 $condition = " AND v.component_id={$campaignCompId}";
292 if (!$includePetitionActivityType) {
293 $condition .= " AND v.name != 'Petition'";
295 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
302 if (!empty($activityTypes[$cacheKey])) {
303 return $activityTypes[$cacheKey];
311 * Get Surveys custom groups.
313 * @param array $surveyTypes
314 * an array of survey type id.
318 public static function getSurveyCustomGroups($surveyTypes = []) {
320 if (!is_array($surveyTypes)) {
321 $surveyTypes = [$surveyTypes];
324 if (!empty($surveyTypes)) {
325 $activityTypes = array_flip($surveyTypes);
328 $activityTypes = self
::getSurveyActivityType();
331 if (!empty($activityTypes)) {
332 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
334 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
335 FROM civicrm_custom_group cg
336 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
338 $dao = CRM_Core_DAO
::executeQuery($query);
339 while ($dao->fetch()) {
340 $customGroups[$dao->id
]['id'] = $dao->id
;
341 $customGroups[$dao->id
]['name'] = $dao->name
;
342 $customGroups[$dao->id
]['title'] = $dao->title
;
343 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
347 return $customGroups;
351 * Update the is_active flag in the db.
354 * Id of the database record.
355 * @param bool $is_active
356 * Value we want to set the is_active field.
359 * true if we found and updated the object, else false
361 public static function setIsActive($id, $is_active) {
362 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
372 public static function del($id) {
376 self
::deleteRecord(['id' => $id]);
381 * Event fired prior to modifying a Survey.
382 * @param \Civi\Core\Event\PreEvent $event
384 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
385 if ($event->action
=== 'delete' && $event->id
) {
386 $reportId = self
::getReportID($event->id
);
388 CRM_Report_BAO_ReportInstance
::deleteRecord(['id' => $reportId]);
394 * This function retrieve contact information.
396 * @param array $voterIds
397 * @param array $returnProperties
398 * An array of return elements.
401 * array of contact info.
403 public static function voterDetails($voterIds, $returnProperties = []) {
405 if (!is_array($voterIds) ||
empty($voterIds)) {
406 return $voterDetails;
409 if (empty($returnProperties)) {
410 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
411 'contact_autocomplete_options'
413 $returnProperties = array_fill_keys(array_merge(
414 ['contact_type', 'contact_sub_type', 'sort_name'],
415 array_keys($autocompleteContactSearch)
419 $select = $from = [];
420 foreach ($returnProperties as $property => $ignore) {
421 $value = (in_array($property, [
424 ])) ?
'address' : $property;
428 case 'contact_sub_type':
429 $select[] = "$property as $property";
430 $from['contact'] = 'civicrm_contact contact';
436 case 'street_address':
437 $select[] = "$property as $property";
438 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
442 case 'state_province':
443 $select[] = "{$property}.name as $property";
444 if (!in_array('address', $from)) {
445 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
447 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
452 //finally retrieve contact details.
453 if (!empty($select) && !empty($from)) {
454 $fromClause = implode(' ', $from);
455 $selectClause = implode(', ', $select);
456 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
459 SELECT contact.id as contactId, $selectClause
463 $contact = CRM_Core_DAO
::executeQuery($query);
464 while ($contact->fetch()) {
465 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
466 foreach ($returnProperties as $property => $ignore) {
467 $voterDetails[$contact->contactId
][$property] = $contact->$property;
469 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
473 $voterDetails[$contact->contactId
]['contact_type'] = $image;
477 return $voterDetails;
481 * This function retrieve survey related activities w/ for give voter ids.
483 * @param int $surveyId
485 * @param array $voterIds
488 * @param int $interviewerId
489 * @param array $statusIds
492 * array of survey activity.
494 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
495 $activityDetails = [];
497 !is_array($voterIds) ||
empty($voterIds)
499 return $activityDetails;
503 if (is_array($statusIds) && !empty($statusIds)) {
504 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
507 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
508 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
509 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
510 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
512 $params[1] = [$surveyId, 'Integer'];
514 SELECT activity.id, activity.status_id,
515 activityTarget.contact_id as voter_id,
516 activityAssignment.contact_id as interviewer_id
517 FROM civicrm_activity activity
518 INNER JOIN civicrm_activity_contact activityTarget
519 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
520 INNER JOIN civicrm_activity_contact activityAssignment
521 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
522 WHERE activity.source_record_id = %1
523 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
524 if (!empty($interviewerId)) {
525 $query .= "AND activityAssignment.contact_id = %2 ";
526 $params[2] = [$interviewerId, 'Integer'];
528 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
530 $activity = CRM_Core_DAO
::executeQuery($query, $params);
531 while ($activity->fetch()) {
532 $activityDetails[$activity->voter_id
] = [
533 'voter_id' => $activity->voter_id
,
534 'status_id' => $activity->status_id
,
535 'activity_id' => $activity->id
,
536 'interviewer_id' => $activity->interviewer_id
,
540 return $activityDetails;
544 * This function retrieve survey related activities.
546 * @param int $surveyId
547 * @param int $interviewerId
548 * @param array $statusIds
549 * @param array $voterIds
550 * @param bool $onlyCount
553 * An array of survey activity, or an int if $onlyCount is set to TRUE
555 public static function getSurveyActivities(
557 $interviewerId = NULL,
563 $surveyActivityCount = 0;
565 return ($onlyCount) ?
0 : $activities;
569 if (!empty($statusIds)) {
570 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
573 if ($interviewerId) {
574 $where[] = "( activityAssignment.contact_id = $interviewerId )";
577 if (!empty($voterIds)) {
578 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
582 if (!empty($where)) {
583 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
586 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
592 $select = "SELECT count(activity.id)";
596 SELECT activity.id, activity.status_id,
597 activityTarget.contact_id as voter_id,
598 activityAssignment.contact_id as interviewer_id,
599 activity.result as result,
600 activity.activity_date_time as activity_date_time,
601 contact_a.display_name as voter_name";
604 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
605 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
606 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
610 FROM civicrm_activity activity
611 INNER JOIN civicrm_activity_contact activityTarget
612 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
613 INNER JOIN civicrm_activity_contact activityAssignment
614 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
615 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
616 WHERE activity.source_record_id = %1
617 AND activity.activity_type_id = %2
618 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
622 1 => [$surveyId, 'Integer'],
623 2 => [$actTypeId, 'Integer'],
627 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
628 return ($dbCount) ?
$dbCount : 0;
631 $activity = CRM_Core_DAO
::executeQuery($query, $params);
633 while ($activity->fetch()) {
634 $activities[$activity->id
] = [
635 'id' => $activity->id
,
636 'voter_id' => $activity->voter_id
,
637 'voter_name' => $activity->voter_name
,
638 'status_id' => $activity->status_id
,
639 'interviewer_id' => $activity->interviewer_id
,
640 'result' => $activity->result
,
641 'activity_date_time' => $activity->activity_date_time
,
649 * Retrieve survey voter information.
651 * @param int $surveyId
653 * @param int $interviewerId
655 * @param array $statusIds
659 * Survey related contact ids.
661 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
667 $cacheKey = $surveyId;
668 if ($interviewerId) {
669 $cacheKey .= "_{$interviewerId}";
671 if (is_array($statusIds) && !empty($statusIds)) {
672 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
675 static $contactIds = [];
676 if (!isset($contactIds[$cacheKey])) {
677 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
678 foreach ($activities as $values) {
679 $voterIds[$values['voter_id']] = $values;
681 $contactIds[$cacheKey] = $voterIds;
684 return $contactIds[$cacheKey];
688 * This function retrieve all option groups which are created as a result set.
690 * @param string $valueColumnName
692 * an array of option groups.
694 public static function getResultSets($valueColumnName = 'title') {
696 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
698 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
699 $dao = CRM_Core_DAO
::executeQuery($query);
700 while ($dao->fetch()) {
701 $resultSets[$dao->id
] = $dao->$valueColumnName;
708 * check survey activity.
710 * @param int $activityId
714 public static function isSurveyActivity($activityId) {
715 $isSurveyActivity = FALSE;
717 return $isSurveyActivity;
720 $activity = new CRM_Activity_DAO_Activity();
721 $activity->id
= $activityId;
722 $activity->selectAdd('source_record_id, activity_type_id');
723 if ($activity->find(TRUE) &&
724 $activity->source_record_id
726 $surveyActTypes = self
::getSurveyActivityType();
727 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
728 $isSurveyActivity = TRUE;
732 return $isSurveyActivity;
736 * This function retrive all response options of survey.
738 * @param int $surveyId
741 * an array of option values
743 public static function getResponsesOptions($surveyId) {
744 $responseOptions = [];
746 return $responseOptions;
749 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
751 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
754 return $responseOptions;
758 * This function return all voter links with respecting permissions.
760 * @param int $surveyId
761 * @param bool $enclosedInUL
762 * @param string $extraULName
763 * @return array|string
764 * $url array of permissioned links
766 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
772 static $voterLinks = [];
773 if (empty($voterLinks)) {
774 $permissioned = FALSE;
775 if (CRM_Core_Permission
::check('manage campaign') ||
776 CRM_Core_Permission
::check('administer CiviCampaign')
778 $permissioned = TRUE;
781 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
782 $voterLinks['reserve'] = [
784 'url' => 'civicrm/survey/search',
785 'qs' => 'sid=%%id%%&reset=1&op=reserve',
786 'title' => ts('Reserve Respondents'),
789 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
790 $voterLinks['release'] = [
791 'name' => 'interview',
792 'url' => 'civicrm/survey/search',
793 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
794 'title' => ts('Interview Respondents'),
797 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
798 $voterLinks['interview'] = [
800 'url' => 'civicrm/survey/search',
801 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
802 'title' => ts('Release Respondents'),
807 if (CRM_Core_Permission
::check('access CiviReport')) {
808 $reportID = self
::getReportID($surveyId);
810 $voterLinks['report'] = [
812 'url' => "civicrm/report/instance/{$reportID}",
814 'title' => ts('View Survey Report'),
819 $ids = ['id' => $surveyId];
820 foreach ($voterLinks as $link) {
821 if (!empty($link['qs']) &&
822 !CRM_Utils_System
::isNull($link['qs'])
824 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
825 CRM_Core_Action
::replace($link['qs'], $ids)
827 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
829 CRM_Utils_Array
::value('title', $link),
835 $extraLinksName = strtolower($extraULName);
837 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
838 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
839 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
846 * Retrieve survey associated profile id.
848 * @param int $surveyId
852 public static function getSurveyProfileId($surveyId) {
858 if (!array_key_exists($surveyId, $ufIds)) {
859 //get the profile id.
861 'entity_id' => $surveyId,
862 'entity_table' => 'civicrm_survey',
863 'module' => 'CiviCampaign',
866 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
869 $ufIds[$surveyId] = [$first];
872 $ufIds[$surveyId][] = array_shift($second);
876 return $ufIds[$surveyId] ??
NULL;
880 * @param int $surveyId
884 public static function getReportID($surveyId) {
885 static $reportIds = [];
887 if (!array_key_exists($surveyId, $reportIds)) {
888 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
889 $reportID = CRM_Core_DAO
::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
890 $reportIds[$surveyId] = $reportID;
892 return $reportIds[$surveyId];
896 * Decides the contact type for given survey.
898 * @param int $surveyId
900 * @return null|string
902 public static function getSurveyContactType($surveyId) {
905 //apply filter of profile type on search.
906 $profileId = self
::getSurveyProfileId($surveyId);
908 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
909 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
910 $contactType = $profileType;
918 * Get survey supportable profile types.
920 public static function surveyProfileTypes() {
921 static $profileTypes;
923 if (!isset($profileTypes)) {
924 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType
::basicTypes());
925 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
928 return $profileTypes;
932 * Get the valid survey response fields those.
933 * are configured with profile and custom fields.
935 * @param int $surveyId
937 * @param int $surveyTypeId
938 * Survey activity type id.
941 * an array of valid survey response fields.
943 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
944 if (empty($surveyId)) {
948 static $responseFields;
949 $cacheKey = "{$surveyId}_{$surveyTypeId}";
951 if (isset($responseFields[$cacheKey])) {
952 return $responseFields[$cacheKey];
955 $responseFields[$cacheKey] = [];
957 $profileId = self
::getSurveyProfileId($surveyId);
960 return $responseFields;
963 if (!$surveyTypeId) {
964 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
967 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
968 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
971 //don't load these fields in grid.
972 $removeFields = ['File', 'RichTextEditor'];
974 $supportableFieldTypes = self
::surveyProfileTypes();
976 // get custom fields of type survey
977 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
979 foreach ($profileFields as $name => $field) {
980 //get only contact and activity fields.
981 //later stage we might going to consider contact type also.
982 if (in_array($field['field_type'], $supportableFieldTypes)) {
983 // we should allow all supported custom data for survey
984 // In case of activity, allow normal activity and with subtype survey,
985 // suppress custom data of other activity types
986 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
987 if (!in_array($field['html_type'], $removeFields)) {
988 if ($field['field_type'] != 'Activity') {
989 $responseFields[$cacheKey][$name] = $field;
991 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
992 $responseFields[$cacheKey][$name] = $field;
997 $responseFields[$cacheKey][$name] = $field;
1002 return $responseFields[$cacheKey];
1006 * Get all interviewers of surveys.
1009 * an array of valid survey response fields.
1011 public static function getInterviewers() {
1012 static $interviewers;
1014 if (isset($interviewers)) {
1015 return $interviewers;
1018 $whereClause = NULL;
1019 $activityTypes = self
::getSurveyActivityType();
1020 if (!empty($activityTypes)) {
1021 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1025 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1026 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1029 SELECT contact.id as id,
1030 contact.sort_name as sort_name
1031 FROM civicrm_contact contact
1032 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1033 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1034 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1037 $interviewer = CRM_Core_DAO
::executeQuery($query);
1038 while ($interviewer->fetch()) {
1039 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1042 return $interviewers;
1046 * Check and update the survey respondents.
1048 * @param array $params
1053 public static function releaseRespondent($params) {
1054 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1055 $reserveStatusId = array_search('Scheduled', $activityStatus);
1056 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1057 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1058 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1061 //retrieve all survey activities related to reserve action.
1063 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1065 SELECT activity.id as id,
1066 activity.activity_date_time as activity_date_time,
1067 survey.id as surveyId,
1068 survey.release_frequency as release_frequency
1069 FROM civicrm_activity activity
1070 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1071 WHERE activity.is_deleted = 0
1072 AND activity.status_id = %1
1073 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1074 $activity = CRM_Core_DAO
::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1076 while ($activity->fetch()) {
1077 if (!$activity->release_frequency
) {
1080 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1081 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1082 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1083 if ($totalReservedSeconds < time()) {
1084 $releasedIds[$activity->id
] = $activity->id
;
1088 //released respondent.
1089 if (!empty($releasedIds)) {
1091 UPDATE civicrm_activity
1093 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1094 CRM_Core_DAO
::executeQuery($query);
1095 $releasedCount = count($releasedIds);
1101 'messages' => "Number of respondents released = {$releasedCount}",
1108 * Get options for a given field.
1109 * @see CRM_Core_DAO::buildOptions
1111 * @param string $fieldName
1112 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1113 * @param array $props : whatever is known about this dao object
1115 * @return array|bool
1117 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1119 // Special logic for fields whose options depend on context or properties
1120 switch ($fieldName) {
1121 case 'activity_type_id':
1122 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1123 if ($campaignCompId) {
1124 $params['condition'] = ["component_id={$campaignCompId}"];
1128 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);