Merge pull request #22468 from eileenmcnaughton/ab
[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 /**
fe482240
EM
24 * Retrieve DB object based on input parameters.
25 *
26 * It also stores all the retrieved values in the default array.
6a488035 27 *
7aaf6db0
TO
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.
77b97be7 32 *
c490a46a 33 * @return CRM_Campaign_DAO_Survey|null
6a488035 34 */
00be9182 35 public static function retrieve(&$params, &$defaults) {
6a488035
TO
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 /**
86950de8
SM
48 * Takes an associative array and creates a Survey object based on the
49 * supplied values.
6a488035 50 *
c490a46a 51 * @param array $params
77b97be7 52 *
86950de8 53 * @return bool|CRM_Campaign_DAO_Survey
6a488035 54 */
00be9182 55 public static function create(&$params) {
6a488035 56 if (empty($params)) {
5c2ea586 57 return FALSE;
6a488035
TO
58 }
59
a7488080 60 if (!empty($params['is_default'])) {
6a488035 61 $query = "UPDATE civicrm_survey SET is_default = 0";
33621c4f 62 CRM_Core_DAO::executeQuery($query);
6a488035
TO
63 }
64
0419bf7b
CW
65 if (empty($params['id'])) {
66 if (empty($params['created_id'])) {
67 $params['created_id'] = CRM_Core_Session::getLoggedInContactID();
6a488035 68 }
0419bf7b
CW
69
70 if (empty($params['created_date'])) {
6a488035
TO
71 $params['created_date'] = date('YmdHis');
72 }
73 }
74
0419bf7b 75 $dao = self::writeRecord($params);
86950de8 76
6a488035
TO
77 return $dao;
78 }
79
80 /**
100fef9d 81 * Retrieve surveys for dashboard.
6a488035 82 *
ad37ac8e 83 * @param array $params
84 * @param bool $onlyCount
85 *
86 * @return array|int
6a488035 87 */
be2fb01f 88 public static function getSurveySummary($params = [], $onlyCount = FALSE) {
6a488035
TO
89 //build the limit and order clause.
90 $limitClause = $orderByClause = $lookupTableJoins = NULL;
91 if (!$onlyCount) {
be2fb01f 92 $sortParams = [
6a488035
TO
93 'sort' => 'created_date',
94 'offset' => 0,
95 'rowCount' => 10,
96 'sortOrder' => 'desc',
be2fb01f 97 ];
6a488035 98 foreach ($sortParams as $name => $default) {
a7488080 99 if (!empty($params[$name])) {
6a488035
TO
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 = "
91da6cd5 115 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
6a488035
TO
116 OR survey.activity_type_id IS NULL )
117INNER 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.
be2fb01f 130 $queryParams = $where = [];
6a488035
TO
131
132 //we only have activity type as a
133 //difference between survey and petition.
0571e734 134 $petitionTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
6a488035
TO
135 if ($petitionTypeID) {
136 $where[] = "( survey.activity_type_id != %1 )";
be2fb01f 137 $queryParams[1] = [$petitionTypeID, 'Positive'];
6a488035
TO
138 }
139
a7488080 140 if (!empty($params['title'])) {
6a488035 141 $where[] = "( survey.title LIKE %2 )";
be2fb01f 142 $queryParams[2] = ['%' . trim($params['title']) . '%', 'String'];
6a488035 143 }
a7488080 144 if (!empty($params['campaign_id'])) {
6a488035 145 $where[] = '( survey.campaign_id = %3 )';
be2fb01f 146 $queryParams[3] = [$params['campaign_id'], 'Positive'];
6a488035 147 }
a7488080 148 if (!empty($params['activity_type_id'])) {
6a488035
TO
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 = '
161SELECT 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) {
5c2ea586 180 return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
6a488035
TO
181 }
182
be2fb01f
CW
183 $surveys = [];
184 $properties = [
353ffa53
TO
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',
be2fb01f 195 ];
6a488035
TO
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 *
6a488035 210 */
00be9182 211 public static function getSurveyCount() {
5c2ea586 212 return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
6a488035
TO
213 }
214
215 /**
fe482240 216 * Get Surveys.
6a488035 217 *
7aaf6db0
TO
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.
6a488035 226 *
6a488035 227 */
5c2ea586 228 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
6a488035 229 $cacheKey = 0;
be2fb01f 230 $cacheKeyParams = ['onlyActive', 'onlyDefault', 'forceAll', 'includePetition'];
6a488035
TO
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])) {
9231464f
KJ
242 if (!$includePetition) {
243 //we only have activity type as a
244 //difference between survey and petition.
d66c61b6 245 $petitionTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'petition');
6a488035 246
be2fb01f 247 $where = [];
9231464f
KJ
248 if ($petitionTypeID) {
249 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
250 }
6a488035
TO
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 = "
261SELECT survey.id as id,
262 survey.title as title
263 FROM civicrm_survey as survey
264 WHERE {$whereClause}";
be2fb01f 265 $surveys[$cacheKey] = [];
6a488035
TO
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 /**
8d7a9d07 276 * Get Survey activity types.
ea3ddccf 277 *
278 * @param string $returnColumn
279 * @param bool $includePetitionActivityType
dbb0d30b 280 *
f157740d 281 * @return mixed
6a488035 282 */
8d7a9d07 283 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
6a488035
TO
284 static $activityTypes;
285 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
286
287 if (!isset($activityTypes[$cacheKey])) {
be2fb01f 288 $activityTypes = [];
6a488035
TO
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 }
7b60d5b9 302 if (!empty($activityTypes[$cacheKey])) {
303 return $activityTypes[$cacheKey];
304 }
305 else {
306 return;
307 }
6a488035
TO
308 }
309
310 /**
fe482240 311 * Get Surveys custom groups.
6a488035 312 *
5a4f6742
CW
313 * @param array $surveyTypes
314 * an array of survey type id.
6a488035 315 *
77b97be7 316 * @return array
6a488035 317 */
be2fb01f
CW
318 public static function getSurveyCustomGroups($surveyTypes = []) {
319 $customGroups = [];
6a488035 320 if (!is_array($surveyTypes)) {
be2fb01f 321 $surveyTypes = [$surveyTypes];
6a488035
TO
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 /**
fe482240 351 * Update the is_active flag in the db.
6a488035 352 *
7aaf6db0
TO
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.
6a488035 357 *
8a4fede3 358 * @return bool
359 * true if we found and updated the object, else false
6a488035 360 */
00be9182 361 public static function setIsActive($id, $is_active) {
6a488035
TO
362 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
363 }
364
365 /**
1f591bab 366 * Delete a survey.
6a488035 367 *
7aaf6db0 368 * @param int $id
1f591bab 369 * @deprecated
77b97be7 370 * @return mixed|null
6a488035 371 */
00be9182 372 public static function del($id) {
6a488035
TO
373 if (!$id) {
374 return NULL;
375 }
1f591bab
CW
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 }
6a488035 390 }
6a488035
TO
391 }
392
393 /**
394 * This function retrieve contact information.
395 *
c490a46a 396 * @param array $voterIds
7aaf6db0
TO
397 * @param array $returnProperties
398 * An array of return elements.
6a488035 399 *
a6c01b45
CW
400 * @return array
401 * array of contact info.
6a488035 402 */
be2fb01f
CW
403 public static function voterDetails($voterIds, $returnProperties = []) {
404 $voterDetails = [];
6a488035
TO
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 );
5d4fcf54
TO
413 $returnProperties = array_fill_keys(array_merge(
414 ['contact_type', 'contact_sub_type', 'sort_name'],
353ffa53
TO
415 array_keys($autocompleteContactSearch)
416 ), 1);
6a488035
TO
417 }
418
be2fb01f 419 $select = $from = [];
6a488035 420 foreach ($returnProperties as $property => $ignore) {
be2fb01f 421 $value = (in_array($property, [
353ffa53 422 'city',
8d7a9d07 423 'street_address',
be2fb01f 424 ])) ? 'address' : $property;
6a488035
TO
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)) {
353ffa53 454 $fromClause = implode(' ', $from);
6a488035 455 $selectClause = implode(', ', $select);
353ffa53 456 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
6a488035
TO
457
458 $query = "
91da6cd5 459 SELECT contact.id as contactId, $selectClause
6a488035 460 FROM $fromClause
e5cceea5 461 WHERE $whereClause";
6a488035
TO
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 }
5c2ea586 469 $image = CRM_Contact_BAO_Contact_Utils::getImage($contact->contact_sub_type ? $contact->contact_sub_type : $contact->contact_type,
6a488035
TO
470 FALSE,
471 $contact->contactId
472 );
473 $voterDetails[$contact->contactId]['contact_type'] = $image;
474 }
6a488035
TO
475 }
476
477 return $voterDetails;
478 }
479
480 /**
481 * This function retrieve survey related activities w/ for give voter ids.
482 *
7aaf6db0
TO
483 * @param int $surveyId
484 * Survey id.
485 * @param array $voterIds
486 * VoterIds.
6a488035 487 *
100fef9d 488 * @param int $interviewerId
2a6da8d7
EM
489 * @param array $statusIds
490 *
a6c01b45
CW
491 * @return array
492 * array of survey activity.
6a488035 493 */
be2fb01f
CW
494 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = []) {
495 $activityDetails = [];
6a488035
TO
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
6a488035 507 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
44f817d4 508 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
9e74e3ce 509 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
510 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
8ef12e64 511
be2fb01f 512 $params[1] = [$surveyId, 'Integer'];
91da6cd5
DL
513 $query = "
514 SELECT activity.id, activity.status_id,
baf8a079 515 activityTarget.contact_id as voter_id,
516 activityAssignment.contact_id as interviewer_id
6a488035 517 FROM civicrm_activity activity
91da6cd5 518INNER JOIN civicrm_activity_contact activityTarget
9e74e3ce 519 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
91da6cd5 520INNER JOIN civicrm_activity_contact activityAssignment
9e74e3ce 521 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
6a488035 522 WHERE activity.source_record_id = %1
64e716d7 523 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
22e263ad 524 if (!empty($interviewerId)) {
64e716d7 525 $query .= "AND activityAssignment.contact_id = %2 ";
be2fb01f 526 $params[2] = [$interviewerId, 'Integer'];
64e716d7
JM
527 }
528 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
6a488035 529 $whereClause";
77b97be7 530 $activity = CRM_Core_DAO::executeQuery($query, $params);
6a488035 531 while ($activity->fetch()) {
be2fb01f 532 $activityDetails[$activity->voter_id] = [
6a488035
TO
533 'voter_id' => $activity->voter_id,
534 'status_id' => $activity->status_id,
535 'activity_id' => $activity->id,
536 'interviewer_id' => $activity->interviewer_id,
be2fb01f 537 ];
6a488035
TO
538 }
539
540 return $activityDetails;
541 }
542
543 /**
544 * This function retrieve survey related activities.
545 *
7aaf6db0 546 * @param int $surveyId
100fef9d 547 * @param int $interviewerId
f220017a
CW
548 * @param array $statusIds
549 * @param array $voterIds
2a6da8d7 550 * @param bool $onlyCount
f220017a 551 *
e0f5b841
BT
552 * @return array|int
553 * An array of survey activity, or an int if $onlyCount is set to TRUE
6a488035 554 */
8d7a9d07 555 public static function getSurveyActivities(
5c2ea586 556 $surveyId,
6a488035 557 $interviewerId = NULL,
5c2ea586
TO
558 $statusIds = NULL,
559 $voterIds = NULL,
560 $onlyCount = FALSE
6a488035 561 ) {
be2fb01f 562 $activities = [];
6a488035
TO
563 $surveyActivityCount = 0;
564 if (!$surveyId) {
565 return ($onlyCount) ? 0 : $activities;
566 }
567
be2fb01f 568 $where = [];
6a488035
TO
569 if (!empty($statusIds)) {
570 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
571 }
572
573 if ($interviewerId) {
5161d8be 574 $where[] = "( activityAssignment.contact_id = $interviewerId )";
6a488035
TO
575 }
576
577 if (!empty($voterIds)) {
5161d8be 578 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
6a488035
TO
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 = "
91da6cd5 596 SELECT activity.id, activity.status_id,
5161d8be 597 activityTarget.contact_id as voter_id,
598 activityAssignment.contact_id as interviewer_id,
6a488035
TO
599 activity.result as result,
600 activity.activity_date_time as activity_date_time,
601 contact_a.display_name as voter_name";
602 }
603
44f817d4 604 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
9e74e3ce 605 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
606 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
607
6a488035
TO
608 $query = "
609 $select
610 FROM civicrm_activity activity
91da6cd5 611INNER JOIN civicrm_activity_contact activityTarget
9e74e3ce 612 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
91da6cd5 613INNER JOIN civicrm_activity_contact activityAssignment
9e74e3ce 614 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
91da6cd5 615INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
6a488035
TO
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
be2fb01f
CW
621 $params = [
622 1 => [$surveyId, 'Integer'],
623 2 => [$actTypeId, 'Integer'],
624 ];
6a488035
TO
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()) {
be2fb01f 634 $activities[$activity->id] = [
6a488035
TO
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,
21dfd5f5 641 'activity_date_time' => $activity->activity_date_time,
be2fb01f 642 ];
6a488035
TO
643 }
644
645 return $activities;
646 }
647
648 /**
dc195289 649 * Retrieve survey voter information.
6a488035 650 *
7aaf6db0
TO
651 * @param int $surveyId
652 * Survey id.
653 * @param int $interviewerId
654 * Interviewer id.
655 * @param array $statusIds
656 * Survey status ids.
6a488035 657 *
dc195289
CW
658 * @return array
659 * Survey related contact ids.
6a488035 660 */
be2fb01f
CW
661 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = []) {
662 $voterIds = [];
6a488035
TO
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
be2fb01f 675 static $contactIds = [];
6a488035
TO
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 /**
fe482240 688 * This function retrieve all option groups which are created as a result set.
6a488035 689 *
2a6da8d7 690 * @param string $valueColumnName
a6c01b45
CW
691 * @return array
692 * an array of option groups.
6a488035 693 */
5c2ea586 694 public static function getResultSets($valueColumnName = 'title') {
be2fb01f 695 $resultSets = [];
6a488035
TO
696 $valueColumnName = CRM_Utils_Type::escape($valueColumnName, 'String');
697
353ffa53
TO
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);
6a488035
TO
700 while ($dao->fetch()) {
701 $resultSets[$dao->id] = $dao->$valueColumnName;
702 }
703
704 return $resultSets;
705 }
706
707 /**
dc195289 708 * check survey activity.
6a488035 709 *
7aaf6db0
TO
710 * @param int $activityId
711 * Activity id.
8d7a9d07 712 * @return bool
6a488035 713 */
00be9182 714 public static function isSurveyActivity($activityId) {
6a488035
TO
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 /**
fe482240 736 * This function retrive all response options of survey.
6a488035 737 *
7aaf6db0
TO
738 * @param int $surveyId
739 * Survey id.
a6c01b45
CW
740 * @return array
741 * an array of option values
6a488035 742 */
00be9182 743 public static function getResponsesOptions($surveyId) {
be2fb01f 744 $responseOptions = [];
6a488035
TO
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 /**
fe482240 758 * This function return all voter links with respecting permissions.
6a488035 759 *
100fef9d 760 * @param int $surveyId
2a6da8d7
EM
761 * @param bool $enclosedInUL
762 * @param string $extraULName
72b3a70c
CW
763 * @return array|string
764 * $url array of permissioned links
6a488035 765 */
00be9182 766 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
be2fb01f 767 $menuLinks = [];
6a488035
TO
768 if (!$surveyId) {
769 return $menuLinks;
770 }
771
be2fb01f 772 static $voterLinks = [];
6a488035
TO
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")) {
be2fb01f 782 $voterLinks['reserve'] = [
6a488035
TO
783 'name' => 'reserve',
784 'url' => 'civicrm/survey/search',
2db64250 785 'qs' => 'sid=%%id%%&reset=1&op=reserve',
6a488035 786 'title' => ts('Reserve Respondents'),
be2fb01f 787 ];
6a488035
TO
788 }
789 if ($permissioned || CRM_Core_Permission::check("interview campaign contacts")) {
be2fb01f 790 $voterLinks['release'] = [
6a488035
TO
791 'name' => 'interview',
792 'url' => 'civicrm/survey/search',
793 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
794 'title' => ts('Interview Respondents'),
be2fb01f 795 ];
6a488035
TO
796 }
797 if ($permissioned || CRM_Core_Permission::check("release campaign contacts")) {
be2fb01f 798 $voterLinks['interview'] = [
6a488035
TO
799 'name' => 'release',
800 'url' => 'civicrm/survey/search',
801 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
802 'title' => ts('Release Respondents'),
be2fb01f 803 ];
6a488035
TO
804 }
805 }
806
807 if (CRM_Core_Permission::check('access CiviReport')) {
808 $reportID = self::getReportID($surveyId);
809 if ($reportID) {
be2fb01f 810 $voterLinks['report'] = [
8d7a9d07
CB
811 'name' => 'report',
812 'url' => "civicrm/report/instance/{$reportID}",
813 'qs' => 'reset=1',
814 'title' => ts('View Survey Report'),
be2fb01f 815 ];
6a488035
TO
816 }
817 }
818
be2fb01f 819 $ids = ['id' => $surveyId];
6a488035 820 foreach ($voterLinks as $link) {
a7488080 821 if (!empty($link['qs']) &&
6a488035
TO
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 );
a1c7d42f 827 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
6a488035
TO
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>";
a1c7d42f 839 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
6a488035
TO
840 }
841
842 return $menuLinks;
843 }
844
845 /**
100fef9d 846 * Retrieve survey associated profile id.
ad37ac8e 847 *
848 * @param int $surveyId
849 *
850 * @return mixed|null
6a488035
TO
851 */
852 public static function getSurveyProfileId($surveyId) {
853 if (!$surveyId) {
854 return NULL;
855 }
856
be2fb01f 857 static $ufIds = [];
6a488035
TO
858 if (!array_key_exists($surveyId, $ufIds)) {
859 //get the profile id.
be2fb01f 860 $ufJoinParams = [
6a488035
TO
861 'entity_id' => $surveyId,
862 'entity_table' => 'civicrm_survey',
863 'module' => 'CiviCampaign',
be2fb01f 864 ];
91da6cd5 865
6a488035
TO
866 list($first, $second) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
867
868 if ($first) {
be2fb01f 869 $ufIds[$surveyId] = [$first];
6a488035
TO
870 }
871 if ($second) {
91da6cd5 872 $ufIds[$surveyId][] = array_shift($second);
6a488035
TO
873 }
874 }
875
914d3734 876 return $ufIds[$surveyId] ?? NULL;
6a488035
TO
877 }
878
30c4e065 879 /**
100fef9d 880 * @param int $surveyId
30c4e065
EM
881 *
882 * @return mixed
883 */
5d4fcf54 884 public static function getReportID($surveyId) {
be2fb01f 885 static $reportIds = [];
6a488035
TO
886
887 if (!array_key_exists($surveyId, $reportIds)) {
888 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
be2fb01f 889 $reportID = CRM_Core_DAO::singleValueQuery($query, [1 => ["survey_{$surveyId}", 'String']]);
6a488035
TO
890 $reportIds[$surveyId] = $reportID;
891 }
892 return $reportIds[$surveyId];
893 }
894
895 /**
100fef9d 896 * Decides the contact type for given survey.
ea3ddccf 897 *
898 * @param int $surveyId
899 *
900 * @return null|string
6a488035
TO
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 /**
fe482240 918 * Get survey supportable profile types.
6a488035
TO
919 */
920 public static function surveyProfileTypes() {
921 static $profileTypes;
922
923 if (!isset($profileTypes)) {
be2fb01f
CW
924 $profileTypes = array_merge(['Activity', 'Contact'], CRM_Contact_BAO_ContactType::basicTypes());
925 $profileTypes = array_diff($profileTypes, ['Organization', 'Household']);
6a488035
TO
926 }
927
928 return $profileTypes;
929 }
930
931 /**
fe482240 932 * Get the valid survey response fields those.
6a488035
TO
933 * are configured with profile and custom fields.
934 *
7aaf6db0
TO
935 * @param int $surveyId
936 * Survey id.
937 * @param int $surveyTypeId
938 * Survey activity type id.
6a488035 939 *
a6c01b45
CW
940 * @return array
941 * an array of valid survey response fields.
6a488035
TO
942 */
943 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
944 if (empty($surveyId)) {
be2fb01f 945 return [];
6a488035
TO
946 }
947
948 static $responseFields;
949 $cacheKey = "{$surveyId}_{$surveyTypeId}";
950
951 if (isset($responseFields[$cacheKey])) {
952 return $responseFields[$cacheKey];
953 }
954
be2fb01f 955 $responseFields[$cacheKey] = [];
6a488035
TO
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,
5e5141ea 968 FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE
6a488035
TO
969 );
970
971 //don't load these fields in grid.
be2fb01f 972 $removeFields = ['File', 'RichTextEditor'];
6a488035
TO
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.
4e9ab75a
RN
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 }
6a488035 995 }
4e9ab75a 996 else {
6a488035
TO
997 $responseFields[$cacheKey][$name] = $field;
998 }
999 }
6a488035
TO
1000 }
1001
1002 return $responseFields[$cacheKey];
1003 }
1004
1005 /**
1006 * Get all interviewers of surveys.
1007 *
a6c01b45
CW
1008 * @return array
1009 * an array of valid survey response fields.
6a488035
TO
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
be2fb01f 1024 $interviewers = [];
44f817d4 1025 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
9e74e3ce 1026 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
6a488035
TO
1027
1028 $query = "
91da6cd5 1029 SELECT contact.id as id,
6a488035 1030 contact.sort_name as sort_name
91da6cd5 1031 FROM civicrm_contact contact
9e74e3ce 1032INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
6a488035
TO
1033INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1034INNER 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 *
c490a46a 1048 * @param array $params
dd244018 1049 *
a6c01b45
CW
1050 * @return array
1051 * success message
6a488035 1052 */
7b60d5b9 1053 public static function releaseRespondent($params) {
6a488035
TO
1054 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
1055 $reserveStatusId = array_search('Scheduled', $activityStatus);
1056 $surveyActivityTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
7b60d5b9 1057 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1058 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1059 }
6a488035
TO
1060
1061 //retrieve all survey activities related to reserve action.
1062 $releasedCount = 0;
1063 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1064 $query = '
91da6cd5 1065 SELECT activity.id as id,
6a488035
TO
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
91da6cd5
DL
1070INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1071 WHERE activity.is_deleted = 0
1072 AND activity.status_id = %1
6a488035 1073 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
be2fb01f
CW
1074 $activity = CRM_Core_DAO::executeQuery($query, [1 => [$reserveStatusId, 'Positive']]);
1075 $releasedIds = [];
6a488035
TO
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 = '
1091UPDATE 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
be2fb01f 1099 $rtnMsg = [
6a488035
TO
1100 'is_error' => 0,
1101 'messages' => "Number of respondents released = {$releasedCount}",
be2fb01f 1102 ];
6a488035
TO
1103
1104 return $rtnMsg;
1105 }
a2015e41
CW
1106
1107 /**
1108 * Get options for a given field.
1109 * @see CRM_Core_DAO::buildOptions
1110 *
7aaf6db0 1111 * @param string $fieldName
353ffa53
TO
1112 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1113 * @param array $props : whatever is known about this dao object
a2015e41
CW
1114 *
1115 * @return array|bool
1116 */
be2fb01f
CW
1117 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1118 $params = [];
a2015e41
CW
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) {
be2fb01f 1124 $params['condition'] = ["component_id={$campaignCompId}"];
a2015e41
CW
1125 }
1126 break;
1127 }
1128 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1129 }
96025800 1130
6a488035 1131}