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