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