Merge pull request #20995 from ixiam/dev-import-phone-extension
[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 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 a survey.
370 *
371 * @param int $id
372 * @deprecated
373 * @return mixed|null
374 */
375 public static function del($id) {
376 if (!$id) {
377 return NULL;
378 }
379 self::deleteRecord(['id' => $id]);
380 return 1;
381 }
382
383 /**
384 * Event fired prior to modifying a Survey.
385 * @param \Civi\Core\Event\PreEvent $event
386 */
387 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent $event) {
388 if ($event->action === 'delete' && $event->id) {
389 $reportId = self::getReportID($event->id);
390 if ($reportId) {
391 CRM_Report_BAO_ReportInstance::deleteRecord(['id' => $reportId]);
392 }
393 }
394 }
395
396 /**
397 * This function retrieve contact information.
398 *
399 * @param array $voterIds
400 * @param array $returnProperties
401 * An array of return elements.
402 *
403 * @return array
404 * array of contact info.
405 */
406 public static function voterDetails($voterIds, $returnProperties = []) {
407 $voterDetails = [];
408 if (!is_array($voterIds) || empty($voterIds)) {
409 return $voterDetails;
410 }
411
412 if (empty($returnProperties)) {
413 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
414 'contact_autocomplete_options'
415 );
416 $returnProperties = array_fill_keys(array_merge(
417 ['contact_type', 'contact_sub_type', 'sort_name'],
418 array_keys($autocompleteContactSearch)
419 ), 1);
420 }
421
422 $select = $from = [];
423 foreach ($returnProperties as $property => $ignore) {
424 $value = (in_array($property, [
425 'city',
426 'street_address',
427 ])) ? 'address' : $property;
428 switch ($property) {
429 case 'sort_name':
430 case 'contact_type':
431 case 'contact_sub_type':
432 $select[] = "$property as $property";
433 $from['contact'] = 'civicrm_contact contact';
434 break;
435
436 case 'email':
437 case 'phone':
438 case 'city':
439 case 'street_address':
440 $select[] = "$property as $property";
441 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
442 break;
443
444 case 'country':
445 case 'state_province':
446 $select[] = "{$property}.name as $property";
447 if (!in_array('address', $from)) {
448 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
449 }
450 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
451 break;
452 }
453 }
454
455 //finally retrieve contact details.
456 if (!empty($select) && !empty($from)) {
457 $fromClause = implode(' ', $from);
458 $selectClause = implode(', ', $select);
459 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
460
461 $query = "
462 SELECT contact.id as contactId, $selectClause
463 FROM $fromClause
464 WHERE $whereClause";
465
466 $contact = CRM_Core_DAO::executeQuery($query);
467 while ($contact->fetch()) {
468 $voterDetails[$contact->contactId]['contact_id'] = $contact->contactId;
469 foreach ($returnProperties as $property => $ignore) {
470 $voterDetails[$contact->contactId][$property] = $contact->$property;
471 }
472 $image = CRM_Contact_BAO_Contact_Utils::getImage($contact->contact_sub_type ? $contact->contact_sub_type : $contact->contact_type,
473 FALSE,
474 $contact->contactId
475 );
476 $voterDetails[$contact->contactId]['contact_type'] = $image;
477 }
478 }
479
480 return $voterDetails;
481 }
482
483 /**
484 * This function retrieve survey related activities w/ for give voter ids.
485 *
486 * @param int $surveyId
487 * Survey id.
488 * @param array $voterIds
489 * VoterIds.
490 *
491 * @param int $interviewerId
492 * @param array $statusIds
493 *
494 * @return array
495 * array of survey activity.
496 */
497 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
498 $activityDetails = [];
499 if (!$surveyId ||
500 !is_array($voterIds) || empty($voterIds)
501 ) {
502 return $activityDetails;
503 }
504
505 $whereClause = NULL;
506 if (is_array($statusIds) && !empty($statusIds)) {
507 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
508 }
509
510 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
511 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
512 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
513 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
514
515 $params[1] = [$surveyId, 'Integer'];
516 $query = "
517 SELECT activity.id, activity.status_id,
518 activityTarget.contact_id as voter_id,
519 activityAssignment.contact_id as interviewer_id
520 FROM civicrm_activity activity
521 INNER JOIN civicrm_activity_contact activityTarget
522 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
523 INNER JOIN civicrm_activity_contact activityAssignment
524 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
525 WHERE activity.source_record_id = %1
526 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
527 if (!empty($interviewerId)) {
528 $query .= "AND activityAssignment.contact_id = %2 ";
529 $params[2] = [$interviewerId, 'Integer'];
530 }
531 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
532 $whereClause";
533 $activity = CRM_Core_DAO::executeQuery($query, $params);
534 while ($activity->fetch()) {
535 $activityDetails[$activity->voter_id] = [
536 'voter_id' => $activity->voter_id,
537 'status_id' => $activity->status_id,
538 'activity_id' => $activity->id,
539 'interviewer_id' => $activity->interviewer_id,
540 ];
541 }
542
543 return $activityDetails;
544 }
545
546 /**
547 * This function retrieve survey related activities.
548 *
549 * @param int $surveyId
550 * @param int $interviewerId
551 * @param array $statusIds
552 * @param array $voterIds
553 * @param bool $onlyCount
554 *
555 * @return array
556 * An array of survey activity.
557 */
558 public static function getSurveyActivities(
559 $surveyId,
560 $interviewerId = NULL,
561 $statusIds = NULL,
562 $voterIds = NULL,
563 $onlyCount = FALSE
564 ) {
565 $activities = [];
566 $surveyActivityCount = 0;
567 if (!$surveyId) {
568 return ($onlyCount) ? 0 : $activities;
569 }
570
571 $where = [];
572 if (!empty($statusIds)) {
573 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
574 }
575
576 if ($interviewerId) {
577 $where[] = "( activityAssignment.contact_id = $interviewerId )";
578 }
579
580 if (!empty($voterIds)) {
581 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
582 }
583
584 $whereClause = NULL;
585 if (!empty($where)) {
586 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
587 }
588
589 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
590 if (!$actTypeId) {
591 return $activities;
592 }
593
594 if ($onlyCount) {
595 $select = "SELECT count(activity.id)";
596 }
597 else {
598 $select = "
599 SELECT activity.id, activity.status_id,
600 activityTarget.contact_id as voter_id,
601 activityAssignment.contact_id as interviewer_id,
602 activity.result as result,
603 activity.activity_date_time as activity_date_time,
604 contact_a.display_name as voter_name";
605 }
606
607 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
608 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
609 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
610
611 $query = "
612 $select
613 FROM civicrm_activity activity
614 INNER JOIN civicrm_activity_contact activityTarget
615 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
616 INNER JOIN civicrm_activity_contact activityAssignment
617 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
618 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
619 WHERE activity.source_record_id = %1
620 AND activity.activity_type_id = %2
621 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
622 $whereClause";
623
624 $params = [
625 1 => [$surveyId, 'Integer'],
626 2 => [$actTypeId, 'Integer'],
627 ];
628
629 if ($onlyCount) {
630 $dbCount = CRM_Core_DAO::singleValueQuery($query, $params);
631 return ($dbCount) ? $dbCount : 0;
632 }
633
634 $activity = CRM_Core_DAO::executeQuery($query, $params);
635
636 while ($activity->fetch()) {
637 $activities[$activity->id] = [
638 'id' => $activity->id,
639 'voter_id' => $activity->voter_id,
640 'voter_name' => $activity->voter_name,
641 'status_id' => $activity->status_id,
642 'interviewer_id' => $activity->interviewer_id,
643 'result' => $activity->result,
644 'activity_date_time' => $activity->activity_date_time,
645 ];
646 }
647
648 return $activities;
649 }
650
651 /**
652 * Retrieve survey voter information.
653 *
654 * @param int $surveyId
655 * Survey id.
656 * @param int $interviewerId
657 * Interviewer id.
658 * @param array $statusIds
659 * Survey status ids.
660 *
661 * @return array
662 * Survey related contact ids.
663 */
664 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
665 $voterIds = [];
666 if (!$surveyId) {
667 return $voterIds;
668 }
669
670 $cacheKey = $surveyId;
671 if ($interviewerId) {
672 $cacheKey .= "_{$interviewerId}";
673 }
674 if (is_array($statusIds) && !empty($statusIds)) {
675 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
676 }
677
678 static $contactIds = [];
679 if (!isset($contactIds[$cacheKey])) {
680 $activities = self::getSurveyActivities($surveyId, $interviewerId, $statusIds);
681 foreach ($activities as $values) {
682 $voterIds[$values['voter_id']] = $values;
683 }
684 $contactIds[$cacheKey] = $voterIds;
685 }
686
687 return $contactIds[$cacheKey];
688 }
689
690 /**
691 * This function retrieve all option groups which are created as a result set.
692 *
693 * @param string $valueColumnName
694 * @return array
695 * an array of option groups.
696 */
697 public static function getResultSets($valueColumnName = 'title') {
698 $resultSets = [];
699 $valueColumnName = CRM_Utils_Type::escape($valueColumnName, 'String');
700
701 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
702 $dao = CRM_Core_DAO::executeQuery($query);
703 while ($dao->fetch()) {
704 $resultSets[$dao->id] = $dao->$valueColumnName;
705 }
706
707 return $resultSets;
708 }
709
710 /**
711 * check survey activity.
712 *
713 * @param int $activityId
714 * Activity id.
715 * @return bool
716 */
717 public static function isSurveyActivity($activityId) {
718 $isSurveyActivity = FALSE;
719 if (!$activityId) {
720 return $isSurveyActivity;
721 }
722
723 $activity = new CRM_Activity_DAO_Activity();
724 $activity->id = $activityId;
725 $activity->selectAdd('source_record_id, activity_type_id');
726 if ($activity->find(TRUE) &&
727 $activity->source_record_id
728 ) {
729 $surveyActTypes = self::getSurveyActivityType();
730 if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
731 $isSurveyActivity = TRUE;
732 }
733 }
734
735 return $isSurveyActivity;
736 }
737
738 /**
739 * This function retrive all response options of survey.
740 *
741 * @param int $surveyId
742 * Survey id.
743 * @return array
744 * an array of option values
745 */
746 public static function getResponsesOptions($surveyId) {
747 $responseOptions = [];
748 if (!$surveyId) {
749 return $responseOptions;
750 }
751
752 $resultId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
753 if ($resultId) {
754 $responseOptions = CRM_Core_OptionGroup::valuesByID($resultId);
755 }
756
757 return $responseOptions;
758 }
759
760 /**
761 * This function return all voter links with respecting permissions.
762 *
763 * @param int $surveyId
764 * @param bool $enclosedInUL
765 * @param string $extraULName
766 * @return array|string
767 * $url array of permissioned links
768 */
769 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
770 $menuLinks = [];
771 if (!$surveyId) {
772 return $menuLinks;
773 }
774
775 static $voterLinks = [];
776 if (empty($voterLinks)) {
777 $permissioned = FALSE;
778 if (CRM_Core_Permission::check('manage campaign') ||
779 CRM_Core_Permission::check('administer CiviCampaign')
780 ) {
781 $permissioned = TRUE;
782 }
783
784 if ($permissioned || CRM_Core_Permission::check("reserve campaign contacts")) {
785 $voterLinks['reserve'] = [
786 'name' => 'reserve',
787 'url' => 'civicrm/survey/search',
788 'qs' => 'sid=%%id%%&reset=1&op=reserve',
789 'title' => ts('Reserve Respondents'),
790 ];
791 }
792 if ($permissioned || CRM_Core_Permission::check("interview campaign contacts")) {
793 $voterLinks['release'] = [
794 'name' => 'interview',
795 'url' => 'civicrm/survey/search',
796 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
797 'title' => ts('Interview Respondents'),
798 ];
799 }
800 if ($permissioned || CRM_Core_Permission::check("release campaign contacts")) {
801 $voterLinks['interview'] = [
802 'name' => 'release',
803 'url' => 'civicrm/survey/search',
804 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
805 'title' => ts('Release Respondents'),
806 ];
807 }
808 }
809
810 if (CRM_Core_Permission::check('access CiviReport')) {
811 $reportID = self::getReportID($surveyId);
812 if ($reportID) {
813 $voterLinks['report'] = [
814 'name' => 'report',
815 'url' => "civicrm/report/instance/{$reportID}",
816 'qs' => 'reset=1',
817 'title' => ts('View Survey Report'),
818 ];
819 }
820 }
821
822 $ids = ['id' => $surveyId];
823 foreach ($voterLinks as $link) {
824 if (!empty($link['qs']) &&
825 !CRM_Utils_System::isNull($link['qs'])
826 ) {
827 $urlPath = CRM_Utils_System::url(CRM_Core_Action::replace($link['url'], $ids),
828 CRM_Core_Action::replace($link['qs'], $ids)
829 );
830 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
831 $urlPath,
832 CRM_Utils_Array::value('title', $link),
833 $link['title']
834 );
835 }
836 }
837 if ($enclosedInUL) {
838 $extraLinksName = strtolower($extraULName);
839 $allLinks = '';
840 CRM_Utils_String::append($allLinks, '</li><li>', $menuLinks);
841 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
842 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
843 }
844
845 return $menuLinks;
846 }
847
848 /**
849 * Retrieve survey associated profile id.
850 *
851 * @param int $surveyId
852 *
853 * @return mixed|null
854 */
855 public static function getSurveyProfileId($surveyId) {
856 if (!$surveyId) {
857 return NULL;
858 }
859
860 static $ufIds = [];
861 if (!array_key_exists($surveyId, $ufIds)) {
862 //get the profile id.
863 $ufJoinParams = [
864 'entity_id' => $surveyId,
865 'entity_table' => 'civicrm_survey',
866 'module' => 'CiviCampaign',
867 ];
868
869 list($first, $second) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
870
871 if ($first) {
872 $ufIds[$surveyId] = [$first];
873 }
874 if ($second) {
875 $ufIds[$surveyId][] = array_shift($second);
876 }
877 }
878
879 return $ufIds[$surveyId] ?? NULL;
880 }
881
882 /**
883 * @param int $surveyId
884 *
885 * @return mixed
886 */
887 public static function getReportID($surveyId) {
888 static $reportIds = [];
889
890 if (!array_key_exists($surveyId, $reportIds)) {
891 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
892 $reportID = CRM_Core_DAO::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
893 $reportIds[$surveyId] = $reportID;
894 }
895 return $reportIds[$surveyId];
896 }
897
898 /**
899 * Decides the contact type for given survey.
900 *
901 * @param int $surveyId
902 *
903 * @return null|string
904 */
905 public static function getSurveyContactType($surveyId) {
906 $contactType = NULL;
907
908 //apply filter of profile type on search.
909 $profileId = self::getSurveyProfileId($surveyId);
910 if ($profileId) {
911 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
912 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
913 $contactType = $profileType;
914 }
915 }
916
917 return $contactType;
918 }
919
920 /**
921 * Get survey supportable profile types.
922 */
923 public static function surveyProfileTypes() {
924 static $profileTypes;
925
926 if (!isset($profileTypes)) {
927 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType::basicTypes());
928 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
929 }
930
931 return $profileTypes;
932 }
933
934 /**
935 * Get the valid survey response fields those.
936 * are configured with profile and custom fields.
937 *
938 * @param int $surveyId
939 * Survey id.
940 * @param int $surveyTypeId
941 * Survey activity type id.
942 *
943 * @return array
944 * an array of valid survey response fields.
945 */
946 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
947 if (empty($surveyId)) {
948 return [];
949 }
950
951 static $responseFields;
952 $cacheKey = "{$surveyId}_{$surveyTypeId}";
953
954 if (isset($responseFields[$cacheKey])) {
955 return $responseFields[$cacheKey];
956 }
957
958 $responseFields[$cacheKey] = [];
959
960 $profileId = self::getSurveyProfileId($surveyId);
961
962 if (!$profileId) {
963 return $responseFields;
964 }
965
966 if (!$surveyTypeId) {
967 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
968 }
969
970 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileId,
971 FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE
972 );
973
974 //don't load these fields in grid.
975 $removeFields = ['File', 'RichTextEditor'];
976
977 $supportableFieldTypes = self::surveyProfileTypes();
978
979 // get custom fields of type survey
980 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyTypeId);
981
982 foreach ($profileFields as $name => $field) {
983 //get only contact and activity fields.
984 //later stage we might going to consider contact type also.
985 if (in_array($field['field_type'], $supportableFieldTypes)) {
986 // we should allow all supported custom data for survey
987 // In case of activity, allow normal activity and with subtype survey,
988 // suppress custom data of other activity types
989 if (CRM_Core_BAO_CustomField::getKeyID($name)) {
990 if (!in_array($field['html_type'], $removeFields)) {
991 if ($field['field_type'] != 'Activity') {
992 $responseFields[$cacheKey][$name] = $field;
993 }
994 elseif (array_key_exists(CRM_Core_BAO_CustomField::getKeyID($name), $customFields)) {
995 $responseFields[$cacheKey][$name] = $field;
996 }
997 }
998 }
999 else {
1000 $responseFields[$cacheKey][$name] = $field;
1001 }
1002 }
1003 }
1004
1005 return $responseFields[$cacheKey];
1006 }
1007
1008 /**
1009 * Get all interviewers of surveys.
1010 *
1011 * @return array
1012 * an array of valid survey response fields.
1013 */
1014 public static function getInterviewers() {
1015 static $interviewers;
1016
1017 if (isset($interviewers)) {
1018 return $interviewers;
1019 }
1020
1021 $whereClause = NULL;
1022 $activityTypes = self::getSurveyActivityType();
1023 if (!empty($activityTypes)) {
1024 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1025 }
1026
1027 $interviewers = [];
1028 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1029 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1030
1031 $query = "
1032 SELECT contact.id as id,
1033 contact.sort_name as sort_name
1034 FROM civicrm_contact contact
1035 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1036 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1037 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1038 {$whereClause}";
1039
1040 $interviewer = CRM_Core_DAO::executeQuery($query);
1041 while ($interviewer->fetch()) {
1042 $interviewers[$interviewer->id] = $interviewer->sort_name;
1043 }
1044
1045 return $interviewers;
1046 }
1047
1048 /**
1049 * Check and update the survey respondents.
1050 *
1051 * @param array $params
1052 *
1053 * @return array
1054 * success message
1055 */
1056 public static function releaseRespondent($params) {
1057 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
1058 $reserveStatusId = array_search('Scheduled', $activityStatus);
1059 $surveyActivityTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
1060 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1061 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1062 }
1063
1064 //retrieve all survey activities related to reserve action.
1065 $releasedCount = 0;
1066 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1067 $query = '
1068 SELECT activity.id as id,
1069 activity.activity_date_time as activity_date_time,
1070 survey.id as surveyId,
1071 survey.release_frequency as release_frequency
1072 FROM civicrm_activity activity
1073 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1074 WHERE activity.is_deleted = 0
1075 AND activity.status_id = %1
1076 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1077 $activity = CRM_Core_DAO::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1078 $releasedIds = [];
1079 while ($activity->fetch()) {
1080 if (!$activity->release_frequency) {
1081 continue;
1082 }
1083 $reservedSeconds = CRM_Utils_Date::unixTime($activity->activity_date_time);
1084 $releasedSeconds = $activity->release_frequency * 24 * 3600;
1085 $totalReservedSeconds = $reservedSeconds + $releasedSeconds;
1086 if ($totalReservedSeconds < time()) {
1087 $releasedIds[$activity->id] = $activity->id;
1088 }
1089 }
1090
1091 //released respondent.
1092 if (!empty($releasedIds)) {
1093 $query = '
1094 UPDATE civicrm_activity
1095 SET is_deleted = 1
1096 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1097 CRM_Core_DAO::executeQuery($query);
1098 $releasedCount = count($releasedIds);
1099 }
1100 }
1101
1102 $rtnMsg = [
1103 'is_error' => 0,
1104 'messages' => "Number of respondents released = {$releasedCount}",
1105 ];
1106
1107 return $rtnMsg;
1108 }
1109
1110 /**
1111 * Get options for a given field.
1112 * @see CRM_Core_DAO::buildOptions
1113 *
1114 * @param string $fieldName
1115 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1116 * @param array $props : whatever is known about this dao object
1117 *
1118 * @return array|bool
1119 */
1120 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1121 $params = [];
1122 // Special logic for fields whose options depend on context or properties
1123 switch ($fieldName) {
1124 case 'activity_type_id':
1125 $campaignCompId = CRM_Core_Component::getComponentID('CiviCampaign');
1126 if ($campaignCompId) {
1127 $params['condition'] = ["component_id={$campaignCompId}"];
1128 }
1129 break;
1130 }
1131 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1132 }
1133
1134 }