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