Merge pull request #17656 from civicrm/5.27
[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 {
22
23 /**
24 * Retrieve DB object based on input parameters.
25 *
26 * It also stores all the retrieved values in the default array.
27 *
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.
32 *
33 * @return CRM_Campaign_DAO_Survey|null
34 */
35 public static function retrieve(&$params, &$defaults) {
36 $dao = new CRM_Campaign_DAO_Survey();
37
38 $dao->copyValues($params);
39
40 if ($dao->find(TRUE)) {
41 CRM_Core_DAO::storeValues($dao, $defaults);
42 return $dao;
43 }
44 return NULL;
45 }
46
47 /**
48 * Takes an associative array and creates a Survey object based on the
49 * supplied values.
50 *
51 * @param array $params
52 *
53 * @return bool|CRM_Campaign_DAO_Survey
54 */
55 public static function create(&$params) {
56 if (empty($params)) {
57 return FALSE;
58 }
59
60 if (!empty($params['is_default'])) {
61 $query = "UPDATE civicrm_survey SET is_default = 0";
62 CRM_Core_DAO::executeQuery($query);
63 }
64
65 if (empty($params['id'])) {
66 if (empty($params['created_id'])) {
67 $params['created_id'] = CRM_Core_Session::getLoggedInContactID();
68 }
69
70 if (empty($params['created_date'])) {
71 $params['created_date'] = date('YmdHis');
72 }
73 }
74
75 $dao = self::writeRecord($params);
76
77 if (!empty($params['custom']) && is_array($params['custom'])) {
78 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_survey', $dao->id);
79 }
80 return $dao;
81 }
82
83 /**
84 * Retrieve surveys for dashboard.
85 *
86 * @param array $params
87 * @param bool $onlyCount
88 *
89 * @return array|int
90 */
91 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
92 //build the limit and order clause.
93 $limitClause = $orderByClause = $lookupTableJoins = NULL;
94 if (!$onlyCount) {
95 $sortParams = [
96 'sort' => 'created_date',
97 'offset' => 0,
98 'rowCount' => 10,
99 'sortOrder' => 'desc',
100 ];
101 foreach ($sortParams as $name => $default) {
102 if (!empty($params[$name])) {
103 $sortParams[$name] = $params[$name];
104 }
105 }
106
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']}";
114 }
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']}";
122 }
123 elseif ($sortParams['sort'] == 'isActive') {
124 $sortParams['sort'] = 'is_active';
125 }
126 if ($orderOnSurveyTable) {
127 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
128 }
129 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
130 }
131
132 //build the where clause.
133 $queryParams = $where = [];
134
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'];
141 }
142
143 if (!empty($params['title'])) {
144 $where[] = "( survey.title LIKE %2 )";
145 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
146 }
147 if (!empty($params['campaign_id'])) {
148 $where[] = '( survey.campaign_id = %3 )';
149 $queryParams[3] = [$params['campaign_id'], 'Positive'];
150 }
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']);
155 }
156 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
157 }
158 $whereClause = NULL;
159 if (!empty($where)) {
160 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
161 }
162
163 $selectClause = '
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';
174 if ($onlyCount) {
175 $selectClause = 'SELECT COUNT(*)';
176 }
177 $fromClause = 'FROM civicrm_survey survey';
178
179 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
180
181 //return only count.
182 if ($onlyCount) {
183 return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
184 }
185
186 $surveys = [];
187 $properties = [
188 'id',
189 'title',
190 'campaign_id',
191 'is_active',
192 'is_default',
193 'result_id',
194 'activity_type_id',
195 'release_frequency',
196 'max_number_of_contacts',
197 'default_number_of_contacts',
198 ];
199
200 $survey = CRM_Core_DAO::executeQuery($query, $queryParams);
201 while ($survey->fetch()) {
202 foreach ($properties as $property) {
203 $surveys[$survey->id][$property] = $survey->$property;
204 }
205 }
206
207 return $surveys;
208 }
209
210 /**
211 * Get the survey count.
212 *
213 */
214 public static function getSurveyCount() {
215 return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
216 }
217
218 /**
219 * Get Surveys.
220 *
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.
229 *
230 */
231 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
232 $cacheKey = 0;
233 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
234 foreach ($cacheKeyParams as $param) {
235 $cacheParam = $$param;
236 if (!$cacheParam) {
237 $cacheParam = 0;
238 }
239 $cacheKey .= '_' . $cacheParam;
240 }
241
242 static $surveys;
243
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');
249
250 $where = [];
251 if ($petitionTypeID) {
252 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
253 }
254 }
255 if (!$forceAll && $onlyActive) {
256 $where[] = '( survey.is_active = 1 )';
257 }
258 if (!$forceAll && $onlyDefault) {
259 $where[] = '( survey.is_default = 1 )';
260 }
261 $whereClause = implode(' AND ', $where);
262
263 $query = "
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;
272 }
273 }
274
275 return $surveys[$cacheKey];
276 }
277
278 /**
279 * Get Survey activity types.
280 *
281 * @param string $returnColumn
282 * @param bool $includePetitionActivityType
283 *
284 * @return mixed
285 */
286 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
287 static $activityTypes;
288 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
289
290 if (!isset($activityTypes[$cacheKey])) {
291 $activityTypes = [];
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'";
297 }
298 $activityTypes[$cacheKey] = CRM_Core_OptionGroup::values('activity_type',
299 FALSE, FALSE, FALSE,
300 $condition,
301 $returnColumn
302 );
303 }
304 }
305 if (!empty($activityTypes[$cacheKey])) {
306 return $activityTypes[$cacheKey];
307 }
308 else {
309 return;
310 }
311 }
312
313 /**
314 * Get Surveys custom groups.
315 *
316 * @param array $surveyTypes
317 * an array of survey type id.
318 *
319 * @return array
320 */
321 public static function getSurveyCustomGroups($surveyTypes = []) {
322 $customGroups = [];
323 if (!is_array($surveyTypes)) {
324 $surveyTypes = [$surveyTypes];
325 }
326
327 if (!empty($surveyTypes)) {
328 $activityTypes = array_flip($surveyTypes);
329 }
330 else {
331 $activityTypes = self::getSurveyActivityType();
332 }
333
334 if (!empty($activityTypes)) {
335 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
336
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}[[:>:]]'";
340
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;
347 }
348 }
349
350 return $customGroups;
351 }
352
353 /**
354 * Update the is_active flag in the db.
355 *
356 * @param int $id
357 * Id of the database record.
358 * @param bool $is_active
359 * Value we want to set the is_active field.
360 *
361 * @return bool
362 * true if we found and updated the object, else false
363 */
364 public static function setIsActive($id, $is_active) {
365 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
366 }
367
368 /**
369 * Delete the survey.
370 *
371 * @param int $id
372 * Survey id.
373 *
374 * @return mixed|null
375 */
376 public static function del($id) {
377 if (!$id) {
378 return NULL;
379 }
380 $reportId = CRM_Campaign_BAO_Survey::getReportID($id);
381 if ($reportId) {
382 CRM_Report_BAO_ReportInstance::del($reportId);
383 }
384 $dao = new CRM_Campaign_DAO_Survey();
385 $dao->id = $id;
386 return $dao->delete();
387 }
388
389 /**
390 * This function retrieve contact information.
391 *
392 * @param array $voterIds
393 * @param array $returnProperties
394 * An array of return elements.
395 *
396 * @return array
397 * array of contact info.
398 */
399 public static function voterDetails($voterIds, $returnProperties = []) {
400 $voterDetails = [];
401 if (!is_array($voterIds) || empty($voterIds)) {
402 return $voterDetails;
403 }
404
405 if (empty($returnProperties)) {
406 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
407 'contact_autocomplete_options'
408 );
409 $returnProperties = array_fill_keys(array_merge(
410 ['contact_type', 'contact_sub_type', 'sort_name'],
411 array_keys($autocompleteContactSearch)
412 ), 1);
413 }
414
415 $select = $from = [];
416 foreach ($returnProperties as $property => $ignore) {
417 $value = (in_array($property, [
418 'city',
419 'street_address',
420 ])) ? 'address' : $property;
421 switch ($property) {
422 case 'sort_name':
423 case 'contact_type':
424 case 'contact_sub_type':
425 $select[] = "$property as $property";
426 $from['contact'] = 'civicrm_contact contact';
427 break;
428
429 case 'email':
430 case 'phone':
431 case 'city':
432 case 'street_address':
433 $select[] = "$property as $property";
434 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
435 break;
436
437 case 'country':
438 case 'state_province':
439 $select[] = "{$property}.name as $property";
440 if (!in_array('address', $from)) {
441 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
442 }
443 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
444 break;
445 }
446 }
447
448 //finally retrieve contact details.
449 if (!empty($select) && !empty($from)) {
450 $fromClause = implode(' ', $from);
451 $selectClause = implode(', ', $select);
452 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
453
454 $query = "
455 SELECT contact.id as contactId, $selectClause
456 FROM $fromClause
457 WHERE $whereClause";
458
459 $contact = CRM_Core_DAO::executeQuery($query);
460 while ($contact->fetch()) {
461 $voterDetails[$contact->contactId]['contact_id'] = $contact->contactId;
462 foreach ($returnProperties as $property => $ignore) {
463 $voterDetails[$contact->contactId][$property] = $contact->$property;
464 }
465 $image = CRM_Contact_BAO_Contact_Utils::getImage($contact->contact_sub_type ? $contact->contact_sub_type : $contact->contact_type,
466 FALSE,
467 $contact->contactId
468 );
469 $voterDetails[$contact->contactId]['contact_type'] = $image;
470 }
471 }
472
473 return $voterDetails;
474 }
475
476 /**
477 * This function retrieve survey related activities w/ for give voter ids.
478 *
479 * @param int $surveyId
480 * Survey id.
481 * @param array $voterIds
482 * VoterIds.
483 *
484 * @param int $interviewerId
485 * @param array $statusIds
486 *
487 * @return array
488 * array of survey activity.
489 */
490 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
491 $activityDetails = [];
492 if (!$surveyId ||
493 !is_array($voterIds) || empty($voterIds)
494 ) {
495 return $activityDetails;
496 }
497
498 $whereClause = NULL;
499 if (is_array($statusIds) && !empty($statusIds)) {
500 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
501 }
502
503 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
504 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
505 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
506 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
507
508 $params[1] = [$surveyId, 'Integer'];
509 $query = "
510 SELECT activity.id, activity.status_id,
511 activityTarget.contact_id as voter_id,
512 activityAssignment.contact_id as interviewer_id
513 FROM civicrm_activity activity
514 INNER JOIN civicrm_activity_contact activityTarget
515 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
516 INNER JOIN civicrm_activity_contact activityAssignment
517 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
518 WHERE activity.source_record_id = %1
519 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
520 if (!empty($interviewerId)) {
521 $query .= "AND activityAssignment.contact_id = %2 ";
522 $params[2] = [$interviewerId, 'Integer'];
523 }
524 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
525 $whereClause";
526 $activity = CRM_Core_DAO::executeQuery($query, $params);
527 while ($activity->fetch()) {
528 $activityDetails[$activity->voter_id] = [
529 'voter_id' => $activity->voter_id,
530 'status_id' => $activity->status_id,
531 'activity_id' => $activity->id,
532 'interviewer_id' => $activity->interviewer_id,
533 ];
534 }
535
536 return $activityDetails;
537 }
538
539 /**
540 * This function retrieve survey related activities.
541 *
542 * @param int $surveyId
543 * @param int $interviewerId
544 * @param array $statusIds
545 * @param array $voterIds
546 * @param bool $onlyCount
547 *
548 * @return array
549 * An array of survey activity.
550 */
551 public static function getSurveyActivities(
552 $surveyId,
553 $interviewerId = NULL,
554 $statusIds = NULL,
555 $voterIds = NULL,
556 $onlyCount = FALSE
557 ) {
558 $activities = [];
559 $surveyActivityCount = 0;
560 if (!$surveyId) {
561 return ($onlyCount) ? 0 : $activities;
562 }
563
564 $where = [];
565 if (!empty($statusIds)) {
566 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
567 }
568
569 if ($interviewerId) {
570 $where[] = "( activityAssignment.contact_id = $interviewerId )";
571 }
572
573 if (!empty($voterIds)) {
574 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
575 }
576
577 $whereClause = NULL;
578 if (!empty($where)) {
579 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
580 }
581
582 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
583 if (!$actTypeId) {
584 return $activities;
585 }
586
587 if ($onlyCount) {
588 $select = "SELECT count(activity.id)";
589 }
590 else {
591 $select = "
592 SELECT activity.id, activity.status_id,
593 activityTarget.contact_id as voter_id,
594 activityAssignment.contact_id as interviewer_id,
595 activity.result as result,
596 activity.activity_date_time as activity_date_time,
597 contact_a.display_name as voter_name";
598 }
599
600 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
601 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
602 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
603
604 $query = "
605 $select
606 FROM civicrm_activity activity
607 INNER JOIN civicrm_activity_contact activityTarget
608 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
609 INNER JOIN civicrm_activity_contact activityAssignment
610 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
611 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
612 WHERE activity.source_record_id = %1
613 AND activity.activity_type_id = %2
614 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
615 $whereClause";
616
617 $params = [
618 1 => [$surveyId, 'Integer'],
619 2 => [$actTypeId, 'Integer'],
620 ];
621
622 if ($onlyCount) {
623 $dbCount = CRM_Core_DAO::singleValueQuery($query, $params);
624 return ($dbCount) ? $dbCount : 0;
625 }
626
627 $activity = CRM_Core_DAO::executeQuery($query, $params);
628
629 while ($activity->fetch()) {
630 $activities[$activity->id] = [
631 'id' => $activity->id,
632 'voter_id' => $activity->voter_id,
633 'voter_name' => $activity->voter_name,
634 'status_id' => $activity->status_id,
635 'interviewer_id' => $activity->interviewer_id,
636 'result' => $activity->result,
637 'activity_date_time' => $activity->activity_date_time,
638 ];
639 }
640
641 return $activities;
642 }
643
644 /**
645 * Retrieve survey voter information.
646 *
647 * @param int $surveyId
648 * Survey id.
649 * @param int $interviewerId
650 * Interviewer id.
651 * @param array $statusIds
652 * Survey status ids.
653 *
654 * @return array
655 * Survey related contact ids.
656 */
657 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
658 $voterIds = [];
659 if (!$surveyId) {
660 return $voterIds;
661 }
662
663 $cacheKey = $surveyId;
664 if ($interviewerId) {
665 $cacheKey .= "_{$interviewerId}";
666 }
667 if (is_array($statusIds) && !empty($statusIds)) {
668 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
669 }
670
671 static $contactIds = [];
672 if (!isset($contactIds[$cacheKey])) {
673 $activities = self::getSurveyActivities($surveyId, $interviewerId, $statusIds);
674 foreach ($activities as $values) {
675 $voterIds[$values['voter_id']] = $values;
676 }
677 $contactIds[$cacheKey] = $voterIds;
678 }
679
680 return $contactIds[$cacheKey];
681 }
682
683 /**
684 * This function retrieve all option groups which are created as a result set.
685 *
686 * @param string $valueColumnName
687 * @return array
688 * an array of option groups.
689 */
690 public static function getResultSets($valueColumnName = 'title') {
691 $resultSets = [];
692 $valueColumnName = CRM_Utils_Type::escape($valueColumnName, 'String');
693
694 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
695 $dao = CRM_Core_DAO::executeQuery($query);
696 while ($dao->fetch()) {
697 $resultSets[$dao->id] = $dao->$valueColumnName;
698 }
699
700 return $resultSets;
701 }
702
703 /**
704 * check survey activity.
705 *
706 * @param int $activityId
707 * Activity id.
708 * @return bool
709 */
710 public static function isSurveyActivity($activityId) {
711 $isSurveyActivity = FALSE;
712 if (!$activityId) {
713 return $isSurveyActivity;
714 }
715
716 $activity = new CRM_Activity_DAO_Activity();
717 $activity->id = $activityId;
718 $activity->selectAdd('source_record_id, activity_type_id');
719 if ($activity->find(TRUE) &&
720 $activity->source_record_id
721 ) {
722 $surveyActTypes = self::getSurveyActivityType();
723 if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
724 $isSurveyActivity = TRUE;
725 }
726 }
727
728 return $isSurveyActivity;
729 }
730
731 /**
732 * This function retrive all response options of survey.
733 *
734 * @param int $surveyId
735 * Survey id.
736 * @return array
737 * an array of option values
738 */
739 public static function getResponsesOptions($surveyId) {
740 $responseOptions = [];
741 if (!$surveyId) {
742 return $responseOptions;
743 }
744
745 $resultId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
746 if ($resultId) {
747 $responseOptions = CRM_Core_OptionGroup::valuesByID($resultId);
748 }
749
750 return $responseOptions;
751 }
752
753 /**
754 * This function return all voter links with respecting permissions.
755 *
756 * @param int $surveyId
757 * @param bool $enclosedInUL
758 * @param string $extraULName
759 * @return array|string
760 * $url array of permissioned links
761 */
762 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
763 $menuLinks = [];
764 if (!$surveyId) {
765 return $menuLinks;
766 }
767
768 static $voterLinks = [];
769 if (empty($voterLinks)) {
770 $permissioned = FALSE;
771 if (CRM_Core_Permission::check('manage campaign') ||
772 CRM_Core_Permission::check('administer CiviCampaign')
773 ) {
774 $permissioned = TRUE;
775 }
776
777 if ($permissioned || CRM_Core_Permission::check("reserve campaign contacts")) {
778 $voterLinks['reserve'] = [
779 'name' => 'reserve',
780 'url' => 'civicrm/survey/search',
781 'qs' => 'sid=%%id%%&reset=1&op=reserve',
782 'title' => ts('Reserve Respondents'),
783 ];
784 }
785 if ($permissioned || CRM_Core_Permission::check("interview campaign contacts")) {
786 $voterLinks['release'] = [
787 'name' => 'interview',
788 'url' => 'civicrm/survey/search',
789 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
790 'title' => ts('Interview Respondents'),
791 ];
792 }
793 if ($permissioned || CRM_Core_Permission::check("release campaign contacts")) {
794 $voterLinks['interview'] = [
795 'name' => 'release',
796 'url' => 'civicrm/survey/search',
797 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
798 'title' => ts('Release Respondents'),
799 ];
800 }
801 }
802
803 if (CRM_Core_Permission::check('access CiviReport')) {
804 $reportID = self::getReportID($surveyId);
805 if ($reportID) {
806 $voterLinks['report'] = [
807 'name' => 'report',
808 'url' => "civicrm/report/instance/{$reportID}",
809 'qs' => 'reset=1',
810 'title' => ts('View Survey Report'),
811 ];
812 }
813 }
814
815 $ids = ['id' => $surveyId];
816 foreach ($voterLinks as $link) {
817 if (!empty($link['qs']) &&
818 !CRM_Utils_System::isNull($link['qs'])
819 ) {
820 $urlPath = CRM_Utils_System::url(CRM_Core_Action::replace($link['url'], $ids),
821 CRM_Core_Action::replace($link['qs'], $ids)
822 );
823 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
824 $urlPath,
825 CRM_Utils_Array::value('title', $link),
826 $link['title']
827 );
828 }
829 }
830 if ($enclosedInUL) {
831 $extraLinksName = strtolower($extraULName);
832 $allLinks = '';
833 CRM_Utils_String::append($allLinks, '</li><li>', $menuLinks);
834 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
835 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
836 }
837
838 return $menuLinks;
839 }
840
841 /**
842 * Retrieve survey associated profile id.
843 *
844 * @param int $surveyId
845 *
846 * @return mixed|null
847 */
848 public static function getSurveyProfileId($surveyId) {
849 if (!$surveyId) {
850 return NULL;
851 }
852
853 static $ufIds = [];
854 if (!array_key_exists($surveyId, $ufIds)) {
855 //get the profile id.
856 $ufJoinParams = [
857 'entity_id' => $surveyId,
858 'entity_table' => 'civicrm_survey',
859 'module' => 'CiviCampaign',
860 ];
861
862 list($first, $second) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
863
864 if ($first) {
865 $ufIds[$surveyId] = [$first];
866 }
867 if ($second) {
868 $ufIds[$surveyId][] = array_shift($second);
869 }
870 }
871
872 return $ufIds[$surveyId] ?? NULL;
873 }
874
875 /**
876 * @param int $surveyId
877 *
878 * @return mixed
879 */
880 public static function getReportID($surveyId) {
881 static $reportIds = [];
882
883 if (!array_key_exists($surveyId, $reportIds)) {
884 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
885 $reportID = CRM_Core_DAO::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
886 $reportIds[$surveyId] = $reportID;
887 }
888 return $reportIds[$surveyId];
889 }
890
891 /**
892 * Decides the contact type for given survey.
893 *
894 * @param int $surveyId
895 *
896 * @return null|string
897 */
898 public static function getSurveyContactType($surveyId) {
899 $contactType = NULL;
900
901 //apply filter of profile type on search.
902 $profileId = self::getSurveyProfileId($surveyId);
903 if ($profileId) {
904 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
905 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
906 $contactType = $profileType;
907 }
908 }
909
910 return $contactType;
911 }
912
913 /**
914 * Get survey supportable profile types.
915 */
916 public static function surveyProfileTypes() {
917 static $profileTypes;
918
919 if (!isset($profileTypes)) {
920 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType::basicTypes());
921 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
922 }
923
924 return $profileTypes;
925 }
926
927 /**
928 * Get the valid survey response fields those.
929 * are configured with profile and custom fields.
930 *
931 * @param int $surveyId
932 * Survey id.
933 * @param int $surveyTypeId
934 * Survey activity type id.
935 *
936 * @return array
937 * an array of valid survey response fields.
938 */
939 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
940 if (empty($surveyId)) {
941 return [];
942 }
943
944 static $responseFields;
945 $cacheKey = "{$surveyId}_{$surveyTypeId}";
946
947 if (isset($responseFields[$cacheKey])) {
948 return $responseFields[$cacheKey];
949 }
950
951 $responseFields[$cacheKey] = [];
952
953 $profileId = self::getSurveyProfileId($surveyId);
954
955 if (!$profileId) {
956 return $responseFields;
957 }
958
959 if (!$surveyTypeId) {
960 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
961 }
962
963 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileId,
964 FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE
965 );
966
967 //don't load these fields in grid.
968 $removeFields = ['File', 'RichTextEditor'];
969
970 $supportableFieldTypes = self::surveyProfileTypes();
971
972 // get custom fields of type survey
973 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyTypeId);
974
975 foreach ($profileFields as $name => $field) {
976 //get only contact and activity fields.
977 //later stage we might going to consider contact type also.
978 if (in_array($field['field_type'], $supportableFieldTypes)) {
979 // we should allow all supported custom data for survey
980 // In case of activity, allow normal activity and with subtype survey,
981 // suppress custom data of other activity types
982 if (CRM_Core_BAO_CustomField::getKeyID($name)) {
983 if (!in_array($field['html_type'], $removeFields)) {
984 if ($field['field_type'] != 'Activity') {
985 $responseFields[$cacheKey][$name] = $field;
986 }
987 elseif (array_key_exists(CRM_Core_BAO_CustomField::getKeyID($name), $customFields)) {
988 $responseFields[$cacheKey][$name] = $field;
989 }
990 }
991 }
992 else {
993 $responseFields[$cacheKey][$name] = $field;
994 }
995 }
996 }
997
998 return $responseFields[$cacheKey];
999 }
1000
1001 /**
1002 * Get all interviewers of surveys.
1003 *
1004 * @return array
1005 * an array of valid survey response fields.
1006 */
1007 public static function getInterviewers() {
1008 static $interviewers;
1009
1010 if (isset($interviewers)) {
1011 return $interviewers;
1012 }
1013
1014 $whereClause = NULL;
1015 $activityTypes = self::getSurveyActivityType();
1016 if (!empty($activityTypes)) {
1017 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1018 }
1019
1020 $interviewers = [];
1021 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1022 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1023
1024 $query = "
1025 SELECT contact.id as id,
1026 contact.sort_name as sort_name
1027 FROM civicrm_contact contact
1028 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1029 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1030 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1031 {$whereClause}";
1032
1033 $interviewer = CRM_Core_DAO::executeQuery($query);
1034 while ($interviewer->fetch()) {
1035 $interviewers[$interviewer->id] = $interviewer->sort_name;
1036 }
1037
1038 return $interviewers;
1039 }
1040
1041 /**
1042 * Check and update the survey respondents.
1043 *
1044 * @param array $params
1045 *
1046 * @return array
1047 * success message
1048 */
1049 public static function releaseRespondent($params) {
1050 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
1051 $reserveStatusId = array_search('Scheduled', $activityStatus);
1052 $surveyActivityTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
1053 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1054 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1055 }
1056
1057 //retrieve all survey activities related to reserve action.
1058 $releasedCount = 0;
1059 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1060 $query = '
1061 SELECT activity.id as id,
1062 activity.activity_date_time as activity_date_time,
1063 survey.id as surveyId,
1064 survey.release_frequency as release_frequency
1065 FROM civicrm_activity activity
1066 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1067 WHERE activity.is_deleted = 0
1068 AND activity.status_id = %1
1069 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1070 $activity = CRM_Core_DAO::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1071 $releasedIds = [];
1072 while ($activity->fetch()) {
1073 if (!$activity->release_frequency) {
1074 continue;
1075 }
1076 $reservedSeconds = CRM_Utils_Date::unixTime($activity->activity_date_time);
1077 $releasedSeconds = $activity->release_frequency * 24 * 3600;
1078 $totalReservedSeconds = $reservedSeconds + $releasedSeconds;
1079 if ($totalReservedSeconds < time()) {
1080 $releasedIds[$activity->id] = $activity->id;
1081 }
1082 }
1083
1084 //released respondent.
1085 if (!empty($releasedIds)) {
1086 $query = '
1087 UPDATE civicrm_activity
1088 SET is_deleted = 1
1089 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1090 CRM_Core_DAO::executeQuery($query);
1091 $releasedCount = count($releasedIds);
1092 }
1093 }
1094
1095 $rtnMsg = [
1096 'is_error' => 0,
1097 'messages' => "Number of respondents released = {$releasedCount}",
1098 ];
1099
1100 return $rtnMsg;
1101 }
1102
1103 /**
1104 * Get options for a given field.
1105 * @see CRM_Core_DAO::buildOptions
1106 *
1107 * @param string $fieldName
1108 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1109 * @param array $props : whatever is known about this dao object
1110 *
1111 * @return array|bool
1112 */
1113 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1114 $params = [];
1115 // Special logic for fields whose options depend on context or properties
1116 switch ($fieldName) {
1117 case 'activity_type_id':
1118 $campaignCompId = CRM_Core_Component::getComponentID('CiviCampaign');
1119 if ($campaignCompId) {
1120 $params['condition'] = ["component_id={$campaignCompId}"];
1121 }
1122 break;
1123 }
1124 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1125 }
1126
1127 }