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 and copy to defaults array.
26 * @param array $params
27 * Array of criteria values.
28 * @param array $defaults
29 * Array to be populated with found values.
32 * The DAO object, if found.
36 public static function retrieve($params, &$defaults) {
37 return self
::commonRetrieve(self
::class, $params, $defaults);
41 * Takes an associative array and creates a Survey object based on the
44 * @param array $params
46 * @return bool|CRM_Campaign_DAO_Survey
48 public static function create(&$params) {
53 if (!empty($params['is_default'])) {
54 $query = "UPDATE civicrm_survey SET is_default = 0";
55 CRM_Core_DAO
::executeQuery($query);
58 if (empty($params['id'])) {
59 if (empty($params['created_id'])) {
60 $params['created_id'] = CRM_Core_Session
::getLoggedInContactID();
63 if (empty($params['created_date'])) {
64 $params['created_date'] = date('YmdHis');
68 $dao = self
::writeRecord($params);
74 * Retrieve surveys for dashboard.
76 * @param array $params
77 * @param bool $onlyCount
81 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
82 //build the limit and order clause.
83 $limitClause = $orderByClause = $lookupTableJoins = NULL;
86 'sort' => 'created_date',
89 'sortOrder' => 'desc',
91 foreach ($sortParams as $name => $default) {
92 if (!empty($params[$name])) {
93 $sortParams[$name] = $params[$name];
97 //need to lookup tables.
98 $orderOnSurveyTable = TRUE;
99 if ($sortParams['sort'] == 'campaign') {
100 $orderOnSurveyTable = FALSE;
101 $lookupTableJoins = '
102 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
103 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
105 elseif ($sortParams['sort'] == 'activity_type') {
106 $orderOnSurveyTable = FALSE;
107 $lookupTableJoins = "
108 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
109 OR survey.activity_type_id IS NULL )
110 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
111 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
113 elseif ($sortParams['sort'] == 'isActive') {
114 $sortParams['sort'] = 'is_active';
116 if ($orderOnSurveyTable) {
117 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
119 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
122 //build the where clause.
123 $queryParams = $where = [];
125 //we only have activity type as a
126 //difference between survey and petition.
127 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
128 if ($petitionTypeID) {
129 $where[] = "( survey.activity_type_id != %1 )";
130 $queryParams[1] = [$petitionTypeID, 'Positive'];
133 if (!empty($params['title'])) {
134 $where[] = "( survey.title LIKE %2 )";
135 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
137 if (!empty($params['campaign_id'])) {
138 $where[] = '( survey.campaign_id = %3 )';
139 $queryParams[3] = [$params['campaign_id'], 'Positive'];
141 if (!empty($params['activity_type_id'])) {
142 $typeId = $params['activity_type_id'];
143 if (is_array($params['activity_type_id'])) {
144 $typeId = implode(' , ', $params['activity_type_id']);
146 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
149 if (!empty($where)) {
150 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
154 SELECT survey.id as id,
155 survey.title as title,
156 survey.is_active as is_active,
157 survey.result_id as result_id,
158 survey.is_default as is_default,
159 survey.campaign_id as campaign_id,
160 survey.activity_type_id as activity_type_id,
161 survey.release_frequency as release_frequency,
162 survey.max_number_of_contacts as max_number_of_contacts,
163 survey.default_number_of_contacts as default_number_of_contacts';
165 $selectClause = 'SELECT COUNT(*)';
167 $fromClause = 'FROM civicrm_survey survey';
169 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
173 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
186 'max_number_of_contacts',
187 'default_number_of_contacts',
190 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
191 while ($survey->fetch()) {
192 foreach ($properties as $property) {
193 $surveys[$survey->id
][$property] = $survey->$property;
201 * Get the survey count.
204 public static function getSurveyCount() {
205 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
211 * @param bool $onlyActive
212 * Retrieve only active surveys.
213 * @param bool $onlyDefault
214 * Retrieve only default survey.
215 * @param bool $forceAll
216 * Retrieve all surveys.
217 * @param bool $includePetition
218 * Include or exclude petitions.
221 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
223 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
224 foreach ($cacheKeyParams as $param) {
225 $cacheParam = $
$param;
229 $cacheKey .= '_' . $cacheParam;
234 if (!isset($surveys[$cacheKey])) {
235 if (!$includePetition) {
236 //we only have activity type as a
237 //difference between survey and petition.
238 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'petition');
241 if ($petitionTypeID) {
242 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
245 if (!$forceAll && $onlyActive) {
246 $where[] = '( survey.is_active = 1 )';
248 if (!$forceAll && $onlyDefault) {
249 $where[] = '( survey.is_default = 1 )';
251 $whereClause = implode(' AND ', $where);
254 SELECT survey.id as id,
255 survey.title as title
256 FROM civicrm_survey as survey
257 WHERE {$whereClause}";
258 $surveys[$cacheKey] = [];
259 $survey = CRM_Core_DAO
::executeQuery($query);
260 while ($survey->fetch()) {
261 $surveys[$cacheKey][$survey->id
] = $survey->title
;
265 return $surveys[$cacheKey];
269 * Get Survey activity types.
271 * @param string $returnColumn
272 * @param bool $includePetitionActivityType
276 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
277 static $activityTypes;
278 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
280 if (!isset($activityTypes[$cacheKey])) {
282 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
283 if ($campaignCompId) {
284 $condition = " AND v.component_id={$campaignCompId}";
285 if (!$includePetitionActivityType) {
286 $condition .= " AND v.name != 'Petition'";
288 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
295 if (!empty($activityTypes[$cacheKey])) {
296 return $activityTypes[$cacheKey];
304 * Get Surveys custom groups.
306 * @param array $surveyTypes
307 * an array of survey type id.
311 public static function getSurveyCustomGroups($surveyTypes = []) {
313 if (!is_array($surveyTypes)) {
314 $surveyTypes = [$surveyTypes];
317 if (!empty($surveyTypes)) {
318 $activityTypes = array_flip($surveyTypes);
321 $activityTypes = self
::getSurveyActivityType();
324 if (!empty($activityTypes)) {
325 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
327 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
328 FROM civicrm_custom_group cg
329 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
331 $dao = CRM_Core_DAO
::executeQuery($query);
332 while ($dao->fetch()) {
333 $customGroups[$dao->id
]['id'] = $dao->id
;
334 $customGroups[$dao->id
]['name'] = $dao->name
;
335 $customGroups[$dao->id
]['title'] = $dao->title
;
336 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
340 return $customGroups;
344 * Update the is_active flag in the db.
347 * Id of the database record.
348 * @param bool $is_active
349 * Value we want to set the is_active field.
352 * true if we found and updated the object, else false
354 public static function setIsActive($id, $is_active) {
355 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
365 public static function del($id) {
369 self
::deleteRecord(['id' => $id]);
374 * Event fired prior to modifying a Survey.
375 * @param \Civi\Core\Event\PreEvent $event
377 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
378 if ($event->action
=== 'delete' && $event->id
) {
379 $reportId = self
::getReportID($event->id
);
381 CRM_Report_BAO_ReportInstance
::deleteRecord(['id' => $reportId]);
387 * This function retrieve contact information.
389 * @param array $voterIds
390 * @param array $returnProperties
391 * An array of return elements.
394 * array of contact info.
396 public static function voterDetails($voterIds, $returnProperties = []) {
398 if (!is_array($voterIds) ||
empty($voterIds)) {
399 return $voterDetails;
402 if (empty($returnProperties)) {
403 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
404 'contact_autocomplete_options'
406 $returnProperties = array_fill_keys(array_merge(
407 ['contact_type', 'contact_sub_type', 'sort_name'],
408 array_keys($autocompleteContactSearch)
412 $select = $from = [];
413 foreach ($returnProperties as $property => $ignore) {
414 $value = (in_array($property, [
417 ])) ?
'address' : $property;
421 case 'contact_sub_type':
422 $select[] = "$property as $property";
423 $from['contact'] = 'civicrm_contact contact';
429 case 'street_address':
430 $select[] = "$property as $property";
431 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
435 case 'state_province':
436 $select[] = "{$property}.name as $property";
437 if (!in_array('address', $from)) {
438 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
440 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
445 //finally retrieve contact details.
446 if (!empty($select) && !empty($from)) {
447 $fromClause = implode(' ', $from);
448 $selectClause = implode(', ', $select);
449 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
452 SELECT contact.id as contactId, $selectClause
456 $contact = CRM_Core_DAO
::executeQuery($query);
457 while ($contact->fetch()) {
458 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
459 foreach ($returnProperties as $property => $ignore) {
460 $voterDetails[$contact->contactId
][$property] = $contact->$property;
462 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
466 $voterDetails[$contact->contactId
]['contact_type'] = $image;
470 return $voterDetails;
474 * This function retrieve survey related activities w/ for give voter ids.
476 * @param int $surveyId
478 * @param array $voterIds
481 * @param int $interviewerId
482 * @param array $statusIds
485 * array of survey activity.
487 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
488 $activityDetails = [];
490 !is_array($voterIds) ||
empty($voterIds)
492 return $activityDetails;
496 if (is_array($statusIds) && !empty($statusIds)) {
497 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
500 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
501 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
502 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
503 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
505 $params[1] = [$surveyId, 'Integer'];
507 SELECT activity.id, activity.status_id,
508 activityTarget.contact_id as voter_id,
509 activityAssignment.contact_id as interviewer_id
510 FROM civicrm_activity activity
511 INNER JOIN civicrm_activity_contact activityTarget
512 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
513 INNER JOIN civicrm_activity_contact activityAssignment
514 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
515 WHERE activity.source_record_id = %1
516 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
517 if (!empty($interviewerId)) {
518 $query .= "AND activityAssignment.contact_id = %2 ";
519 $params[2] = [$interviewerId, 'Integer'];
521 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
523 $activity = CRM_Core_DAO
::executeQuery($query, $params);
524 while ($activity->fetch()) {
525 $activityDetails[$activity->voter_id
] = [
526 'voter_id' => $activity->voter_id
,
527 'status_id' => $activity->status_id
,
528 'activity_id' => $activity->id
,
529 'interviewer_id' => $activity->interviewer_id
,
533 return $activityDetails;
537 * This function retrieve survey related activities.
539 * @param int $surveyId
540 * @param int $interviewerId
541 * @param array $statusIds
542 * @param array $voterIds
543 * @param bool $onlyCount
546 * An array of survey activity, or an int if $onlyCount is set to TRUE
548 public static function getSurveyActivities(
550 $interviewerId = NULL,
556 $surveyActivityCount = 0;
558 return ($onlyCount) ?
0 : $activities;
562 if (!empty($statusIds)) {
563 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
566 if ($interviewerId) {
567 $where[] = "( activityAssignment.contact_id = $interviewerId )";
570 if (!empty($voterIds)) {
571 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
575 if (!empty($where)) {
576 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
579 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
585 $select = "SELECT count(activity.id)";
589 SELECT activity.id, activity.status_id,
590 activityTarget.contact_id as voter_id,
591 activityAssignment.contact_id as interviewer_id,
592 activity.result as result,
593 activity.activity_date_time as activity_date_time,
594 contact_a.display_name as voter_name";
597 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
598 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
599 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
603 FROM civicrm_activity activity
604 INNER JOIN civicrm_activity_contact activityTarget
605 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
606 INNER JOIN civicrm_activity_contact activityAssignment
607 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
608 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
609 WHERE activity.source_record_id = %1
610 AND activity.activity_type_id = %2
611 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
615 1 => [$surveyId, 'Integer'],
616 2 => [$actTypeId, 'Integer'],
620 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
621 return ($dbCount) ?
$dbCount : 0;
624 $activity = CRM_Core_DAO
::executeQuery($query, $params);
626 while ($activity->fetch()) {
627 $activities[$activity->id
] = [
628 'id' => $activity->id
,
629 'voter_id' => $activity->voter_id
,
630 'voter_name' => $activity->voter_name
,
631 'status_id' => $activity->status_id
,
632 'interviewer_id' => $activity->interviewer_id
,
633 'result' => $activity->result
,
634 'activity_date_time' => $activity->activity_date_time
,
642 * Retrieve survey voter information.
644 * @param int $surveyId
646 * @param int $interviewerId
648 * @param array $statusIds
652 * Survey related contact ids.
654 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
660 $cacheKey = $surveyId;
661 if ($interviewerId) {
662 $cacheKey .= "_{$interviewerId}";
664 if (is_array($statusIds) && !empty($statusIds)) {
665 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
668 static $contactIds = [];
669 if (!isset($contactIds[$cacheKey])) {
670 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
671 foreach ($activities as $values) {
672 $voterIds[$values['voter_id']] = $values;
674 $contactIds[$cacheKey] = $voterIds;
677 return $contactIds[$cacheKey];
681 * This function retrieve all option groups which are created as a result set.
683 * @param string $valueColumnName
685 * an array of option groups.
687 public static function getResultSets($valueColumnName = 'title') {
689 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
691 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
692 $dao = CRM_Core_DAO
::executeQuery($query);
693 while ($dao->fetch()) {
694 $resultSets[$dao->id
] = $dao->$valueColumnName;
701 * check survey activity.
703 * @param int $activityId
707 public static function isSurveyActivity($activityId) {
708 $isSurveyActivity = FALSE;
710 return $isSurveyActivity;
713 $activity = new CRM_Activity_DAO_Activity();
714 $activity->id
= $activityId;
715 $activity->selectAdd('source_record_id, activity_type_id');
716 if ($activity->find(TRUE) &&
717 $activity->source_record_id
719 $surveyActTypes = self
::getSurveyActivityType();
720 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
721 $isSurveyActivity = TRUE;
725 return $isSurveyActivity;
729 * This function retrive all response options of survey.
731 * @param int $surveyId
734 * an array of option values
736 public static function getResponsesOptions($surveyId) {
737 $responseOptions = [];
739 return $responseOptions;
742 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
744 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
747 return $responseOptions;
751 * This function return all voter links with respecting permissions.
753 * @param int $surveyId
754 * @param bool $enclosedInUL
755 * @param string $extraULName
756 * @return array|string
757 * $url array of permissioned links
759 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
765 static $voterLinks = [];
766 if (empty($voterLinks)) {
767 $permissioned = FALSE;
768 if (CRM_Core_Permission
::check('manage campaign') ||
769 CRM_Core_Permission
::check('administer CiviCampaign')
771 $permissioned = TRUE;
774 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
775 $voterLinks['reserve'] = [
777 'url' => 'civicrm/survey/search',
778 'qs' => 'sid=%%id%%&reset=1&op=reserve',
779 'title' => ts('Reserve Respondents'),
782 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
783 $voterLinks['release'] = [
784 'name' => 'interview',
785 'url' => 'civicrm/survey/search',
786 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
787 'title' => ts('Interview Respondents'),
790 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
791 $voterLinks['interview'] = [
793 'url' => 'civicrm/survey/search',
794 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
795 'title' => ts('Release Respondents'),
800 if (CRM_Core_Permission
::check('access CiviReport')) {
801 $reportID = self
::getReportID($surveyId);
803 $voterLinks['report'] = [
805 'url' => "civicrm/report/instance/{$reportID}",
807 'title' => ts('View Survey Report'),
812 $ids = ['id' => $surveyId];
813 foreach ($voterLinks as $link) {
814 if (!empty($link['qs']) &&
815 !CRM_Utils_System
::isNull($link['qs'])
817 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
818 CRM_Core_Action
::replace($link['qs'], $ids)
820 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
822 CRM_Utils_Array
::value('title', $link),
828 $extraLinksName = strtolower($extraULName);
830 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
831 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
832 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
839 * Retrieve survey associated profile id.
841 * @param int $surveyId
845 public static function getSurveyProfileId($surveyId) {
851 if (!array_key_exists($surveyId, $ufIds)) {
852 //get the profile id.
854 'entity_id' => $surveyId,
855 'entity_table' => 'civicrm_survey',
856 'module' => 'CiviCampaign',
859 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
862 $ufIds[$surveyId] = [$first];
865 $ufIds[$surveyId][] = array_shift($second);
869 return $ufIds[$surveyId] ??
NULL;
873 * @param int $surveyId
877 public static function getReportID($surveyId) {
878 static $reportIds = [];
880 if (!array_key_exists($surveyId, $reportIds)) {
881 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
882 $reportID = CRM_Core_DAO
::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
883 $reportIds[$surveyId] = $reportID;
885 return $reportIds[$surveyId];
889 * Decides the contact type for given survey.
891 * @param int $surveyId
893 * @return null|string
895 public static function getSurveyContactType($surveyId) {
898 //apply filter of profile type on search.
899 $profileId = self
::getSurveyProfileId($surveyId);
901 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
902 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
903 $contactType = $profileType;
911 * Get survey supportable profile types.
913 public static function surveyProfileTypes() {
914 static $profileTypes;
916 if (!isset($profileTypes)) {
917 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType
::basicTypes());
918 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
921 return $profileTypes;
925 * Get the valid survey response fields those.
926 * are configured with profile and custom fields.
928 * @param int $surveyId
930 * @param int $surveyTypeId
931 * Survey activity type id.
934 * an array of valid survey response fields.
936 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
937 if (empty($surveyId)) {
941 static $responseFields;
942 $cacheKey = "{$surveyId}_{$surveyTypeId}";
944 if (isset($responseFields[$cacheKey])) {
945 return $responseFields[$cacheKey];
948 $responseFields[$cacheKey] = [];
950 $profileId = self
::getSurveyProfileId($surveyId);
953 return $responseFields;
956 if (!$surveyTypeId) {
957 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
960 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
961 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
964 //don't load these fields in grid.
965 $removeFields = ['File', 'RichTextEditor'];
967 $supportableFieldTypes = self
::surveyProfileTypes();
969 // get custom fields of type survey
970 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
972 foreach ($profileFields as $name => $field) {
973 //get only contact and activity fields.
974 //later stage we might going to consider contact type also.
975 if (in_array($field['field_type'], $supportableFieldTypes)) {
976 // we should allow all supported custom data for survey
977 // In case of activity, allow normal activity and with subtype survey,
978 // suppress custom data of other activity types
979 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
980 if (!in_array($field['html_type'], $removeFields)) {
981 if ($field['field_type'] != 'Activity') {
982 $responseFields[$cacheKey][$name] = $field;
984 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
985 $responseFields[$cacheKey][$name] = $field;
990 $responseFields[$cacheKey][$name] = $field;
995 return $responseFields[$cacheKey];
999 * Get all interviewers of surveys.
1002 * an array of valid survey response fields.
1004 public static function getInterviewers() {
1005 static $interviewers;
1007 if (isset($interviewers)) {
1008 return $interviewers;
1011 $whereClause = NULL;
1012 $activityTypes = self
::getSurveyActivityType();
1013 if (!empty($activityTypes)) {
1014 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1018 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1019 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1022 SELECT contact.id as id,
1023 contact.sort_name as sort_name
1024 FROM civicrm_contact contact
1025 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1026 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1027 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1030 $interviewer = CRM_Core_DAO
::executeQuery($query);
1031 while ($interviewer->fetch()) {
1032 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1035 return $interviewers;
1039 * Check and update the survey respondents.
1041 * @param array $params
1046 public static function releaseRespondent($params) {
1047 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1048 $reserveStatusId = array_search('Scheduled', $activityStatus);
1049 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1050 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1051 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1054 //retrieve all survey activities related to reserve action.
1056 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1058 SELECT activity.id as id,
1059 activity.activity_date_time as activity_date_time,
1060 survey.id as surveyId,
1061 survey.release_frequency as release_frequency
1062 FROM civicrm_activity activity
1063 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1064 WHERE activity.is_deleted = 0
1065 AND activity.status_id = %1
1066 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1067 $activity = CRM_Core_DAO
::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1069 while ($activity->fetch()) {
1070 if (!$activity->release_frequency
) {
1073 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1074 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1075 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1076 if ($totalReservedSeconds < time()) {
1077 $releasedIds[$activity->id
] = $activity->id
;
1081 //released respondent.
1082 if (!empty($releasedIds)) {
1084 UPDATE civicrm_activity
1086 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1087 CRM_Core_DAO
::executeQuery($query);
1088 $releasedCount = count($releasedIds);
1094 'messages' => "Number of respondents released = {$releasedCount}",
1101 * Get options for a given field.
1102 * @see CRM_Core_DAO::buildOptions
1104 * @param string $fieldName
1105 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1106 * @param array $props : whatever is known about this dao object
1108 * @return array|bool
1110 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1112 // Special logic for fields whose options depend on context or properties
1113 switch ($fieldName) {
1114 case 'activity_type_id':
1115 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1116 if ($campaignCompId) {
1117 $params['condition'] = ["component_id={$campaignCompId}"];
1121 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);