Merge pull request #22724 from braders/feature/group-search-null-columns
[civicrm-core.git] / CRM / Campaign / BAO / Survey.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Class CRM_Campaign_BAO_Survey.
20 */
21 class CRM_Campaign_BAO_Survey extends CRM_Campaign_DAO_Survey implements Civi\Test\HookInterface {
22
23 /**
24 * Retrieve DB object and copy to defaults array.
25 *
26 * @param array $params
27 * Array of criteria values.
28 * @param array $defaults
29 * Array to be populated with found values.
30 *
31 * @return self|null
32 * The DAO object, if found.
33 *
34 * @deprecated
35 */
36 public static function retrieve($params, &$defaults) {
37 return self::commonRetrieve(self::class, $params, $defaults);
38 }
39
40 /**
41 * Takes an associative array and creates a Survey object based on the
42 * supplied values.
43 *
44 * @param array $params
45 *
46 * @return bool|CRM_Campaign_DAO_Survey
47 */
48 public static function create(&$params) {
49 if (empty($params)) {
50 return FALSE;
51 }
52
53 if (!empty($params['is_default'])) {
54 $query = "UPDATE civicrm_survey SET is_default = 0";
55 CRM_Core_DAO::executeQuery($query);
56 }
57
58 if (empty($params['id'])) {
59 if (empty($params['created_id'])) {
60 $params['created_id'] = CRM_Core_Session::getLoggedInContactID();
61 }
62
63 if (empty($params['created_date'])) {
64 $params['created_date'] = date('YmdHis');
65 }
66 }
67
68 $dao = self::writeRecord($params);
69
70 return $dao;
71 }
72
73 /**
74 * Retrieve surveys for dashboard.
75 *
76 * @param array $params
77 * @param bool $onlyCount
78 *
79 * @return array|int
80 */
81 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
82 //build the limit and order clause.
83 $limitClause = $orderByClause = $lookupTableJoins = NULL;
84 if (!$onlyCount) {
85 $sortParams = [
86 'sort' => 'created_date',
87 'offset' => 0,
88 'rowCount' => 10,
89 'sortOrder' => 'desc',
90 ];
91 foreach ($sortParams as $name => $default) {
92 if (!empty($params[$name])) {
93 $sortParams[$name] = $params[$name];
94 }
95 }
96
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']}";
104 }
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']}";
112 }
113 elseif ($sortParams['sort'] == 'isActive') {
114 $sortParams['sort'] = 'is_active';
115 }
116 if ($orderOnSurveyTable) {
117 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
118 }
119 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
120 }
121
122 //build the where clause.
123 $queryParams = $where = [];
124
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'];
131 }
132
133 if (!empty($params['title'])) {
134 $where[] = "( survey.title LIKE %2 )";
135 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
136 }
137 if (!empty($params['campaign_id'])) {
138 $where[] = '( survey.campaign_id = %3 )';
139 $queryParams[3] = [$params['campaign_id'], 'Positive'];
140 }
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']);
145 }
146 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
147 }
148 $whereClause = NULL;
149 if (!empty($where)) {
150 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
151 }
152
153 $selectClause = '
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';
164 if ($onlyCount) {
165 $selectClause = 'SELECT COUNT(*)';
166 }
167 $fromClause = 'FROM civicrm_survey survey';
168
169 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
170
171 //return only count.
172 if ($onlyCount) {
173 return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
174 }
175
176 $surveys = [];
177 $properties = [
178 'id',
179 'title',
180 'campaign_id',
181 'is_active',
182 'is_default',
183 'result_id',
184 'activity_type_id',
185 'release_frequency',
186 'max_number_of_contacts',
187 'default_number_of_contacts',
188 ];
189
190 $survey = CRM_Core_DAO::executeQuery($query, $queryParams);
191 while ($survey->fetch()) {
192 foreach ($properties as $property) {
193 $surveys[$survey->id][$property] = $survey->$property;
194 }
195 }
196
197 return $surveys;
198 }
199
200 /**
201 * Get the survey count.
202 *
203 */
204 public static function getSurveyCount() {
205 return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
206 }
207
208 /**
209 * Get Surveys.
210 *
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.
219 *
220 */
221 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
222 $cacheKey = 0;
223 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
224 foreach ($cacheKeyParams as $param) {
225 $cacheParam = $$param;
226 if (!$cacheParam) {
227 $cacheParam = 0;
228 }
229 $cacheKey .= '_' . $cacheParam;
230 }
231
232 static $surveys;
233
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');
239
240 $where = [];
241 if ($petitionTypeID) {
242 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
243 }
244 }
245 if (!$forceAll && $onlyActive) {
246 $where[] = '( survey.is_active = 1 )';
247 }
248 if (!$forceAll && $onlyDefault) {
249 $where[] = '( survey.is_default = 1 )';
250 }
251 $whereClause = implode(' AND ', $where);
252
253 $query = "
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;
262 }
263 }
264
265 return $surveys[$cacheKey];
266 }
267
268 /**
269 * Get Survey activity types.
270 *
271 * @param string $returnColumn
272 * @param bool $includePetitionActivityType
273 *
274 * @return mixed
275 */
276 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
277 static $activityTypes;
278 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
279
280 if (!isset($activityTypes[$cacheKey])) {
281 $activityTypes = [];
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'";
287 }
288 $activityTypes[$cacheKey] = CRM_Core_OptionGroup::values('activity_type',
289 FALSE, FALSE, FALSE,
290 $condition,
291 $returnColumn
292 );
293 }
294 }
295 if (!empty($activityTypes[$cacheKey])) {
296 return $activityTypes[$cacheKey];
297 }
298 else {
299 return;
300 }
301 }
302
303 /**
304 * Get Surveys custom groups.
305 *
306 * @param array $surveyTypes
307 * an array of survey type id.
308 *
309 * @return array
310 */
311 public static function getSurveyCustomGroups($surveyTypes = []) {
312 $customGroups = [];
313 if (!is_array($surveyTypes)) {
314 $surveyTypes = [$surveyTypes];
315 }
316
317 if (!empty($surveyTypes)) {
318 $activityTypes = array_flip($surveyTypes);
319 }
320 else {
321 $activityTypes = self::getSurveyActivityType();
322 }
323
324 if (!empty($activityTypes)) {
325 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
326
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}[[:>:]]'";
330
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;
337 }
338 }
339
340 return $customGroups;
341 }
342
343 /**
344 * Update the is_active flag in the db.
345 *
346 * @param int $id
347 * Id of the database record.
348 * @param bool $is_active
349 * Value we want to set the is_active field.
350 *
351 * @return bool
352 * true if we found and updated the object, else false
353 */
354 public static function setIsActive($id, $is_active) {
355 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
356 }
357
358 /**
359 * Delete a survey.
360 *
361 * @param int $id
362 * @deprecated
363 * @return mixed|null
364 */
365 public static function del($id) {
366 if (!$id) {
367 return NULL;
368 }
369 self::deleteRecord(['id' => $id]);
370 return 1;
371 }
372
373 /**
374 * Event fired prior to modifying a Survey.
375 * @param \Civi\Core\Event\PreEvent $event
376 */
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);
380 if ($reportId) {
381 CRM_Report_BAO_ReportInstance::deleteRecord(['id' => $reportId]);
382 }
383 }
384 }
385
386 /**
387 * This function retrieve contact information.
388 *
389 * @param array $voterIds
390 * @param array $returnProperties
391 * An array of return elements.
392 *
393 * @return array
394 * array of contact info.
395 */
396 public static function voterDetails($voterIds, $returnProperties = []) {
397 $voterDetails = [];
398 if (!is_array($voterIds) || empty($voterIds)) {
399 return $voterDetails;
400 }
401
402 if (empty($returnProperties)) {
403 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
404 'contact_autocomplete_options'
405 );
406 $returnProperties = array_fill_keys(array_merge(
407 ['contact_type', 'contact_sub_type', 'sort_name'],
408 array_keys($autocompleteContactSearch)
409 ), 1);
410 }
411
412 $select = $from = [];
413 foreach ($returnProperties as $property => $ignore) {
414 $value = (in_array($property, [
415 'city',
416 'street_address',
417 ])) ? 'address' : $property;
418 switch ($property) {
419 case 'sort_name':
420 case 'contact_type':
421 case 'contact_sub_type':
422 $select[] = "$property as $property";
423 $from['contact'] = 'civicrm_contact contact';
424 break;
425
426 case 'email':
427 case 'phone':
428 case 'city':
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 ) ";
432 break;
433
434 case 'country':
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) ';
439 }
440 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
441 break;
442 }
443 }
444
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) . ')';
450
451 $query = "
452 SELECT contact.id as contactId, $selectClause
453 FROM $fromClause
454 WHERE $whereClause";
455
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;
461 }
462 $image = CRM_Contact_BAO_Contact_Utils::getImage($contact->contact_sub_type ? $contact->contact_sub_type : $contact->contact_type,
463 FALSE,
464 $contact->contactId
465 );
466 $voterDetails[$contact->contactId]['contact_type'] = $image;
467 }
468 }
469
470 return $voterDetails;
471 }
472
473 /**
474 * This function retrieve survey related activities w/ for give voter ids.
475 *
476 * @param int $surveyId
477 * Survey id.
478 * @param array $voterIds
479 * VoterIds.
480 *
481 * @param int $interviewerId
482 * @param array $statusIds
483 *
484 * @return array
485 * array of survey activity.
486 */
487 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
488 $activityDetails = [];
489 if (!$surveyId ||
490 !is_array($voterIds) || empty($voterIds)
491 ) {
492 return $activityDetails;
493 }
494
495 $whereClause = NULL;
496 if (is_array($statusIds) && !empty($statusIds)) {
497 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
498 }
499
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);
504
505 $params[1] = [$surveyId, 'Integer'];
506 $query = "
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'];
520 }
521 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
522 $whereClause";
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,
530 ];
531 }
532
533 return $activityDetails;
534 }
535
536 /**
537 * This function retrieve survey related activities.
538 *
539 * @param int $surveyId
540 * @param int $interviewerId
541 * @param array $statusIds
542 * @param array $voterIds
543 * @param bool $onlyCount
544 *
545 * @return array|int
546 * An array of survey activity, or an int if $onlyCount is set to TRUE
547 */
548 public static function getSurveyActivities(
549 $surveyId,
550 $interviewerId = NULL,
551 $statusIds = NULL,
552 $voterIds = NULL,
553 $onlyCount = FALSE
554 ) {
555 $activities = [];
556 $surveyActivityCount = 0;
557 if (!$surveyId) {
558 return ($onlyCount) ? 0 : $activities;
559 }
560
561 $where = [];
562 if (!empty($statusIds)) {
563 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
564 }
565
566 if ($interviewerId) {
567 $where[] = "( activityAssignment.contact_id = $interviewerId )";
568 }
569
570 if (!empty($voterIds)) {
571 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
572 }
573
574 $whereClause = NULL;
575 if (!empty($where)) {
576 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
577 }
578
579 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
580 if (!$actTypeId) {
581 return $activities;
582 }
583
584 if ($onlyCount) {
585 $select = "SELECT count(activity.id)";
586 }
587 else {
588 $select = "
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";
595 }
596
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);
600
601 $query = "
602 $select
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 )
612 $whereClause";
613
614 $params = [
615 1 => [$surveyId, 'Integer'],
616 2 => [$actTypeId, 'Integer'],
617 ];
618
619 if ($onlyCount) {
620 $dbCount = CRM_Core_DAO::singleValueQuery($query, $params);
621 return ($dbCount) ? $dbCount : 0;
622 }
623
624 $activity = CRM_Core_DAO::executeQuery($query, $params);
625
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,
635 ];
636 }
637
638 return $activities;
639 }
640
641 /**
642 * Retrieve survey voter information.
643 *
644 * @param int $surveyId
645 * Survey id.
646 * @param int $interviewerId
647 * Interviewer id.
648 * @param array $statusIds
649 * Survey status ids.
650 *
651 * @return array
652 * Survey related contact ids.
653 */
654 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
655 $voterIds = [];
656 if (!$surveyId) {
657 return $voterIds;
658 }
659
660 $cacheKey = $surveyId;
661 if ($interviewerId) {
662 $cacheKey .= "_{$interviewerId}";
663 }
664 if (is_array($statusIds) && !empty($statusIds)) {
665 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
666 }
667
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;
673 }
674 $contactIds[$cacheKey] = $voterIds;
675 }
676
677 return $contactIds[$cacheKey];
678 }
679
680 /**
681 * This function retrieve all option groups which are created as a result set.
682 *
683 * @param string $valueColumnName
684 * @return array
685 * an array of option groups.
686 */
687 public static function getResultSets($valueColumnName = 'title') {
688 $resultSets = [];
689 $valueColumnName = CRM_Utils_Type::escape($valueColumnName, 'String');
690
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;
695 }
696
697 return $resultSets;
698 }
699
700 /**
701 * check survey activity.
702 *
703 * @param int $activityId
704 * Activity id.
705 * @return bool
706 */
707 public static function isSurveyActivity($activityId) {
708 $isSurveyActivity = FALSE;
709 if (!$activityId) {
710 return $isSurveyActivity;
711 }
712
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
718 ) {
719 $surveyActTypes = self::getSurveyActivityType();
720 if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
721 $isSurveyActivity = TRUE;
722 }
723 }
724
725 return $isSurveyActivity;
726 }
727
728 /**
729 * This function retrive all response options of survey.
730 *
731 * @param int $surveyId
732 * Survey id.
733 * @return array
734 * an array of option values
735 */
736 public static function getResponsesOptions($surveyId) {
737 $responseOptions = [];
738 if (!$surveyId) {
739 return $responseOptions;
740 }
741
742 $resultId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
743 if ($resultId) {
744 $responseOptions = CRM_Core_OptionGroup::valuesByID($resultId);
745 }
746
747 return $responseOptions;
748 }
749
750 /**
751 * This function return all voter links with respecting permissions.
752 *
753 * @param int $surveyId
754 * @param bool $enclosedInUL
755 * @param string $extraULName
756 * @return array|string
757 * $url array of permissioned links
758 */
759 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
760 $menuLinks = [];
761 if (!$surveyId) {
762 return $menuLinks;
763 }
764
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')
770 ) {
771 $permissioned = TRUE;
772 }
773
774 if ($permissioned || CRM_Core_Permission::check("reserve campaign contacts")) {
775 $voterLinks['reserve'] = [
776 'name' => 'reserve',
777 'url' => 'civicrm/survey/search',
778 'qs' => 'sid=%%id%%&reset=1&op=reserve',
779 'title' => ts('Reserve Respondents'),
780 ];
781 }
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'),
788 ];
789 }
790 if ($permissioned || CRM_Core_Permission::check("release campaign contacts")) {
791 $voterLinks['interview'] = [
792 'name' => 'release',
793 'url' => 'civicrm/survey/search',
794 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
795 'title' => ts('Release Respondents'),
796 ];
797 }
798 }
799
800 if (CRM_Core_Permission::check('access CiviReport')) {
801 $reportID = self::getReportID($surveyId);
802 if ($reportID) {
803 $voterLinks['report'] = [
804 'name' => 'report',
805 'url' => "civicrm/report/instance/{$reportID}",
806 'qs' => 'reset=1',
807 'title' => ts('View Survey Report'),
808 ];
809 }
810 }
811
812 $ids = ['id' => $surveyId];
813 foreach ($voterLinks as $link) {
814 if (!empty($link['qs']) &&
815 !CRM_Utils_System::isNull($link['qs'])
816 ) {
817 $urlPath = CRM_Utils_System::url(CRM_Core_Action::replace($link['url'], $ids),
818 CRM_Core_Action::replace($link['qs'], $ids)
819 );
820 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
821 $urlPath,
822 CRM_Utils_Array::value('title', $link),
823 $link['title']
824 );
825 }
826 }
827 if ($enclosedInUL) {
828 $extraLinksName = strtolower($extraULName);
829 $allLinks = '';
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>";
833 }
834
835 return $menuLinks;
836 }
837
838 /**
839 * Retrieve survey associated profile id.
840 *
841 * @param int $surveyId
842 *
843 * @return mixed|null
844 */
845 public static function getSurveyProfileId($surveyId) {
846 if (!$surveyId) {
847 return NULL;
848 }
849
850 static $ufIds = [];
851 if (!array_key_exists($surveyId, $ufIds)) {
852 //get the profile id.
853 $ufJoinParams = [
854 'entity_id' => $surveyId,
855 'entity_table' => 'civicrm_survey',
856 'module' => 'CiviCampaign',
857 ];
858
859 list($first, $second) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
860
861 if ($first) {
862 $ufIds[$surveyId] = [$first];
863 }
864 if ($second) {
865 $ufIds[$surveyId][] = array_shift($second);
866 }
867 }
868
869 return $ufIds[$surveyId] ?? NULL;
870 }
871
872 /**
873 * @param int $surveyId
874 *
875 * @return mixed
876 */
877 public static function getReportID($surveyId) {
878 static $reportIds = [];
879
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;
884 }
885 return $reportIds[$surveyId];
886 }
887
888 /**
889 * Decides the contact type for given survey.
890 *
891 * @param int $surveyId
892 *
893 * @return null|string
894 */
895 public static function getSurveyContactType($surveyId) {
896 $contactType = NULL;
897
898 //apply filter of profile type on search.
899 $profileId = self::getSurveyProfileId($surveyId);
900 if ($profileId) {
901 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
902 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
903 $contactType = $profileType;
904 }
905 }
906
907 return $contactType;
908 }
909
910 /**
911 * Get survey supportable profile types.
912 */
913 public static function surveyProfileTypes() {
914 static $profileTypes;
915
916 if (!isset($profileTypes)) {
917 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType::basicTypes());
918 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
919 }
920
921 return $profileTypes;
922 }
923
924 /**
925 * Get the valid survey response fields those.
926 * are configured with profile and custom fields.
927 *
928 * @param int $surveyId
929 * Survey id.
930 * @param int $surveyTypeId
931 * Survey activity type id.
932 *
933 * @return array
934 * an array of valid survey response fields.
935 */
936 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
937 if (empty($surveyId)) {
938 return [];
939 }
940
941 static $responseFields;
942 $cacheKey = "{$surveyId}_{$surveyTypeId}";
943
944 if (isset($responseFields[$cacheKey])) {
945 return $responseFields[$cacheKey];
946 }
947
948 $responseFields[$cacheKey] = [];
949
950 $profileId = self::getSurveyProfileId($surveyId);
951
952 if (!$profileId) {
953 return $responseFields;
954 }
955
956 if (!$surveyTypeId) {
957 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
958 }
959
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
962 );
963
964 //don't load these fields in grid.
965 $removeFields = ['File', 'RichTextEditor'];
966
967 $supportableFieldTypes = self::surveyProfileTypes();
968
969 // get custom fields of type survey
970 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyTypeId);
971
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;
983 }
984 elseif (array_key_exists(CRM_Core_BAO_CustomField::getKeyID($name), $customFields)) {
985 $responseFields[$cacheKey][$name] = $field;
986 }
987 }
988 }
989 else {
990 $responseFields[$cacheKey][$name] = $field;
991 }
992 }
993 }
994
995 return $responseFields[$cacheKey];
996 }
997
998 /**
999 * Get all interviewers of surveys.
1000 *
1001 * @return array
1002 * an array of valid survey response fields.
1003 */
1004 public static function getInterviewers() {
1005 static $interviewers;
1006
1007 if (isset($interviewers)) {
1008 return $interviewers;
1009 }
1010
1011 $whereClause = NULL;
1012 $activityTypes = self::getSurveyActivityType();
1013 if (!empty($activityTypes)) {
1014 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1015 }
1016
1017 $interviewers = [];
1018 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1019 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1020
1021 $query = "
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 )
1028 {$whereClause}";
1029
1030 $interviewer = CRM_Core_DAO::executeQuery($query);
1031 while ($interviewer->fetch()) {
1032 $interviewers[$interviewer->id] = $interviewer->sort_name;
1033 }
1034
1035 return $interviewers;
1036 }
1037
1038 /**
1039 * Check and update the survey respondents.
1040 *
1041 * @param array $params
1042 *
1043 * @return array
1044 * success message
1045 */
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);
1052 }
1053
1054 //retrieve all survey activities related to reserve action.
1055 $releasedCount = 0;
1056 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1057 $query = '
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']]);
1068 $releasedIds = [];
1069 while ($activity->fetch()) {
1070 if (!$activity->release_frequency) {
1071 continue;
1072 }
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;
1078 }
1079 }
1080
1081 //released respondent.
1082 if (!empty($releasedIds)) {
1083 $query = '
1084 UPDATE civicrm_activity
1085 SET is_deleted = 1
1086 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1087 CRM_Core_DAO::executeQuery($query);
1088 $releasedCount = count($releasedIds);
1089 }
1090 }
1091
1092 $rtnMsg = [
1093 'is_error' => 0,
1094 'messages' => "Number of respondents released = {$releasedCount}",
1095 ];
1096
1097 return $rtnMsg;
1098 }
1099
1100 /**
1101 * Get options for a given field.
1102 * @see CRM_Core_DAO::buildOptions
1103 *
1104 * @param string $fieldName
1105 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1106 * @param array $props : whatever is known about this dao object
1107 *
1108 * @return array|bool
1109 */
1110 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1111 $params = [];
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}"];
1118 }
1119 break;
1120 }
1121 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1122 }
1123
1124 }