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