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