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