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