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