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