3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
35 * Class CRM_Campaign_BAO_Survey.
37 class CRM_Campaign_BAO_Survey
extends CRM_Campaign_DAO_Survey
{
40 * Retrieve DB object based on input parameters.
42 * It also stores all the retrieved values in the default array.
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
46 * @param array $defaults
47 * (reference ) an assoc array to hold the flattened values.
49 * @return CRM_Campaign_DAO_Survey|null
51 public static function retrieve(&$params, &$defaults) {
52 $dao = new CRM_Campaign_DAO_Survey();
54 $dao->copyValues($params);
56 if ($dao->find(TRUE)) {
57 CRM_Core_DAO
::storeValues($dao, $defaults);
64 * Takes an associative array and creates a Survey object.
66 * the function extract all the params it needs to initialize the create a
70 * @param array $params
72 * @return CRM_Survey_DAO_Survey
74 public static function create(&$params) {
79 if (!empty($params['is_default'])) {
80 $query = "UPDATE civicrm_survey SET is_default = 0";
81 CRM_Core_DAO
::executeQuery($query);
84 if (!(CRM_Utils_Array
::value('id', $params))) {
86 if (!(CRM_Utils_Array
::value('created_id', $params))) {
87 $session = CRM_Core_Session
::singleton();
88 $params['created_id'] = $session->get('userID');
90 if (!(CRM_Utils_Array
::value('created_date', $params))) {
91 $params['created_date'] = date('YmdHis');
95 $dao = new CRM_Campaign_DAO_Survey();
96 $dao->copyValues($params);
99 if (!empty($params['custom']) &&
100 is_array($params['custom'])
102 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
108 * Retrieve surveys for dashboard.
110 * @param array $params
111 * @param bool $onlyCount
115 public static function getSurveySummary($params = array(), $onlyCount = FALSE) {
116 //build the limit and order clause.
117 $limitClause = $orderByClause = $lookupTableJoins = NULL;
120 'sort' => 'created_date',
123 'sortOrder' => 'desc',
125 foreach ($sortParams as $name => $default) {
126 if (!empty($params[$name])) {
127 $sortParams[$name] = $params[$name];
131 //need to lookup tables.
132 $orderOnSurveyTable = TRUE;
133 if ($sortParams['sort'] == 'campaign') {
134 $orderOnSurveyTable = FALSE;
135 $lookupTableJoins = '
136 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
137 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
139 elseif ($sortParams['sort'] == 'activity_type') {
140 $orderOnSurveyTable = FALSE;
141 $lookupTableJoins = "
142 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
143 OR survey.activity_type_id IS NULL )
144 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
145 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
147 elseif ($sortParams['sort'] == 'isActive') {
148 $sortParams['sort'] = 'is_active';
150 if ($orderOnSurveyTable) {
151 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
153 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
156 //build the where clause.
157 $queryParams = $where = array();
159 //we only have activity type as a
160 //difference between survey and petition.
161 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
162 if ($petitionTypeID) {
163 $where[] = "( survey.activity_type_id != %1 )";
164 $queryParams[1] = array($petitionTypeID, 'Positive');
167 if (!empty($params['title'])) {
168 $where[] = "( survey.title LIKE %2 )";
169 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
171 if (!empty($params['campaign_id'])) {
172 $where[] = '( survey.campaign_id = %3 )';
173 $queryParams[3] = array($params['campaign_id'], 'Positive');
175 if (!empty($params['activity_type_id'])) {
176 $typeId = $params['activity_type_id'];
177 if (is_array($params['activity_type_id'])) {
178 $typeId = implode(' , ', $params['activity_type_id']);
180 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
183 if (!empty($where)) {
184 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
188 SELECT survey.id as id,
189 survey.title as title,
190 survey.is_active as is_active,
191 survey.result_id as result_id,
192 survey.is_default as is_default,
193 survey.campaign_id as campaign_id,
194 survey.activity_type_id as activity_type_id,
195 survey.release_frequency as release_frequency,
196 survey.max_number_of_contacts as max_number_of_contacts,
197 survey.default_number_of_contacts as default_number_of_contacts';
199 $selectClause = 'SELECT COUNT(*)';
201 $fromClause = 'FROM civicrm_survey survey';
203 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
207 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
220 'max_number_of_contacts',
221 'default_number_of_contacts',
224 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
225 while ($survey->fetch()) {
226 foreach ($properties as $property) {
227 $surveys[$survey->id
][$property] = $survey->$property;
235 * Get the survey count.
238 public static function getSurveyCount() {
239 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
245 * @param bool $onlyActive
246 * Retrieve only active surveys.
247 * @param bool $onlyDefault
248 * Retrieve only default survey.
249 * @param bool $forceAll
250 * Retrieve all surveys.
251 * @param bool $includePetition
252 * Include or exclude petitions.
255 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
257 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
258 foreach ($cacheKeyParams as $param) {
259 $cacheParam = $
$param;
263 $cacheKey .= '_' . $cacheParam;
268 if (!isset($surveys[$cacheKey])) {
269 if (!$includePetition) {
270 //we only have activity type as a
271 //difference between survey and petition.
272 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
275 if ($petitionTypeID) {
276 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
279 if (!$forceAll && $onlyActive) {
280 $where[] = '( survey.is_active = 1 )';
282 if (!$forceAll && $onlyDefault) {
283 $where[] = '( survey.is_default = 1 )';
285 $whereClause = implode(' AND ', $where);
288 SELECT survey.id as id,
289 survey.title as title
290 FROM civicrm_survey as survey
291 WHERE {$whereClause}";
292 $surveys[$cacheKey] = array();
293 $survey = CRM_Core_DAO
::executeQuery($query);
294 while ($survey->fetch()) {
295 $surveys[$cacheKey][$survey->id
] = $survey->title
;
299 return $surveys[$cacheKey];
303 * Get Survey activity types.
305 * @param string $returnColumn
306 * @param bool $includePetitionActivityType
308 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
309 static $activityTypes;
310 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
312 if (!isset($activityTypes[$cacheKey])) {
313 $activityTypes = array();
314 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
315 if ($campaignCompId) {
316 $condition = " AND v.component_id={$campaignCompId}";
317 if (!$includePetitionActivityType) {
318 $condition .= " AND v.name != 'Petition'";
320 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
327 if (!empty($activityTypes[$cacheKey])) {
328 return $activityTypes[$cacheKey];
336 * Get Surveys custom groups.
338 * @param array $surveyTypes
339 * an array of survey type id.
343 public static function getSurveyCustomGroups($surveyTypes = array()) {
344 $customGroups = array();
345 if (!is_array($surveyTypes)) {
346 $surveyTypes = array($surveyTypes);
349 if (!empty($surveyTypes)) {
350 $activityTypes = array_flip($surveyTypes);
353 $activityTypes = self
::getSurveyActivityType();
356 if (!empty($activityTypes)) {
357 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
359 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
360 FROM civicrm_custom_group cg
361 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
363 $dao = CRM_Core_DAO
::executeQuery($query);
364 while ($dao->fetch()) {
365 $customGroups[$dao->id
]['id'] = $dao->id
;
366 $customGroups[$dao->id
]['name'] = $dao->name
;
367 $customGroups[$dao->id
]['title'] = $dao->title
;
368 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
372 return $customGroups;
376 * Update the is_active flag in the db.
379 * Id of the database record.
380 * @param bool $is_active
381 * Value we want to set the is_active field.
384 * DAO object on success, null otherwise
386 public static function setIsActive($id, $is_active) {
387 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
398 public static function del($id) {
402 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
404 CRM_Report_BAO_ReportInstance
::del($reportId);
406 $dao = new CRM_Campaign_DAO_Survey();
408 return $dao->delete();
412 * This function retrieve contact information.
414 * @param array $voterIds
415 * @param array $returnProperties
416 * An array of return elements.
419 * array of contact info.
421 public static function voterDetails($voterIds, $returnProperties = array()) {
422 $voterDetails = array();
423 if (!is_array($voterIds) ||
empty($voterIds)) {
424 return $voterDetails;
427 if (empty($returnProperties)) {
428 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
429 'contact_autocomplete_options'
431 $returnProperties = array_fill_keys(array_merge(array(
436 array_keys($autocompleteContactSearch)
440 $select = $from = array();
441 foreach ($returnProperties as $property => $ignore) {
442 $value = (in_array($property, array(
445 ))) ?
'address' : $property;
449 case 'contact_sub_type':
450 $select[] = "$property as $property";
451 $from['contact'] = 'civicrm_contact contact';
457 case 'street_address':
458 $select[] = "$property as $property";
459 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
463 case 'state_province':
464 $select[] = "{$property}.name as $property";
465 if (!in_array('address', $from)) {
466 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
468 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
473 //finally retrieve contact details.
474 if (!empty($select) && !empty($from)) {
475 $fromClause = implode(' ', $from);
476 $selectClause = implode(', ', $select);
477 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
480 SELECT contact.id as contactId, $selectClause
484 $contact = CRM_Core_DAO
::executeQuery($query);
485 while ($contact->fetch()) {
486 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
487 foreach ($returnProperties as $property => $ignore) {
488 $voterDetails[$contact->contactId
][$property] = $contact->$property;
490 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
494 $voterDetails[$contact->contactId
]['contact_type'] = $image;
499 return $voterDetails;
503 * This function retrieve survey related activities w/ for give voter ids.
505 * @param int $surveyId
507 * @param array $voterIds
510 * @param int $interviewerId
511 * @param array $statusIds
514 * array of survey activity.
516 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = array()) {
517 $activityDetails = array();
519 !is_array($voterIds) ||
empty($voterIds)
521 return $activityDetails;
525 if (is_array($statusIds) && !empty($statusIds)) {
526 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
529 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
530 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
531 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
532 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
534 $params[1] = array($surveyId, 'Integer');
536 SELECT activity.id, activity.status_id,
537 activityTarget.contact_id as voter_id,
538 activityAssignment.contact_id as interviewer_id
539 FROM civicrm_activity activity
540 INNER JOIN civicrm_activity_contact activityTarget
541 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
542 INNER JOIN civicrm_activity_contact activityAssignment
543 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
544 WHERE activity.source_record_id = %1
545 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
546 if (!empty($interviewerId)) {
547 $query .= "AND activityAssignment.contact_id = %2 ";
548 $params[2] = array($interviewerId, 'Integer');
550 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
552 $activity = CRM_Core_DAO
::executeQuery($query, $params);
553 while ($activity->fetch()) {
554 $activityDetails[$activity->voter_id
] = array(
555 'voter_id' => $activity->voter_id
,
556 'status_id' => $activity->status_id
,
557 'activity_id' => $activity->id
,
558 'interviewer_id' => $activity->interviewer_id
,
562 return $activityDetails;
566 * This function retrieve survey related activities.
568 * @param int $surveyId
569 * @param int $interviewerId
570 * @param array $statusIds
571 * @param array $voterIds
572 * @param bool $onlyCount
575 * An array of survey activity.
577 public static function getSurveyActivities(
579 $interviewerId = NULL,
584 $activities = array();
585 $surveyActivityCount = 0;
587 return ($onlyCount) ?
0 : $activities;
591 if (!empty($statusIds)) {
592 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
595 if ($interviewerId) {
596 $where[] = "( activityAssignment.contact_id = $interviewerId )";
599 if (!empty($voterIds)) {
600 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
604 if (!empty($where)) {
605 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
608 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
614 $select = "SELECT count(activity.id)";
618 SELECT activity.id, activity.status_id,
619 activityTarget.contact_id as voter_id,
620 activityAssignment.contact_id as interviewer_id,
621 activity.result as result,
622 activity.activity_date_time as activity_date_time,
623 contact_a.display_name as voter_name";
626 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
627 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
628 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
632 FROM civicrm_activity activity
633 INNER JOIN civicrm_activity_contact activityTarget
634 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
635 INNER JOIN civicrm_activity_contact activityAssignment
636 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
637 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
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 )
644 1 => array($surveyId, 'Integer'),
645 2 => array($actTypeId, 'Integer'),
649 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
650 return ($dbCount) ?
$dbCount : 0;
653 $activity = CRM_Core_DAO
::executeQuery($query, $params);
655 while ($activity->fetch()) {
656 $activities[$activity->id
] = array(
657 'id' => $activity->id
,
658 'voter_id' => $activity->voter_id
,
659 'voter_name' => $activity->voter_name
,
660 'status_id' => $activity->status_id
,
661 'interviewer_id' => $activity->interviewer_id
,
662 'result' => $activity->result
,
663 'activity_date_time' => $activity->activity_date_time
,
671 * Retrieve survey voter information.
673 * @param int $surveyId
675 * @param int $interviewerId
677 * @param array $statusIds
681 * Survey related contact ids.
683 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
689 $cacheKey = $surveyId;
690 if ($interviewerId) {
691 $cacheKey .= "_{$interviewerId}";
693 if (is_array($statusIds) && !empty($statusIds)) {
694 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
697 static $contactIds = array();
698 if (!isset($contactIds[$cacheKey])) {
699 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
700 foreach ($activities as $values) {
701 $voterIds[$values['voter_id']] = $values;
703 $contactIds[$cacheKey] = $voterIds;
706 return $contactIds[$cacheKey];
710 * This function retrieve all option groups which are created as a result set.
712 * @param string $valueColumnName
714 * an array of option groups.
716 public static function getResultSets($valueColumnName = 'title') {
717 $resultSets = array();
718 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
720 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
721 $dao = CRM_Core_DAO
::executeQuery($query);
722 while ($dao->fetch()) {
723 $resultSets[$dao->id
] = $dao->$valueColumnName;
730 * check survey activity.
732 * @param int $activityId
736 public static function isSurveyActivity($activityId) {
737 $isSurveyActivity = FALSE;
739 return $isSurveyActivity;
742 $activity = new CRM_Activity_DAO_Activity();
743 $activity->id
= $activityId;
744 $activity->selectAdd('source_record_id, activity_type_id');
745 if ($activity->find(TRUE) &&
746 $activity->source_record_id
748 $surveyActTypes = self
::getSurveyActivityType();
749 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
750 $isSurveyActivity = TRUE;
754 return $isSurveyActivity;
758 * This function retrive all response options of survey.
760 * @param int $surveyId
763 * an array of option values
765 public static function getResponsesOptions($surveyId) {
766 $responseOptions = array();
768 return $responseOptions;
771 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
773 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
776 return $responseOptions;
780 * This function return all voter links with respecting permissions.
782 * @param int $surveyId
783 * @param bool $enclosedInUL
784 * @param string $extraULName
785 * @return array|string
786 * $url array of permissioned links
788 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
789 $menuLinks = array();
794 static $voterLinks = array();
795 if (empty($voterLinks)) {
796 $permissioned = FALSE;
797 if (CRM_Core_Permission
::check('manage campaign') ||
798 CRM_Core_Permission
::check('administer CiviCampaign')
800 $permissioned = TRUE;
803 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
804 $voterLinks['reserve'] = array(
806 'url' => 'civicrm/survey/search',
807 'qs' => 'sid=%%id%%&reset=1&op=reserve',
808 'title' => ts('Reserve Respondents'),
811 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
812 $voterLinks['release'] = array(
813 'name' => 'interview',
814 'url' => 'civicrm/survey/search',
815 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
816 'title' => ts('Interview Respondents'),
819 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
820 $voterLinks['interview'] = array(
822 'url' => 'civicrm/survey/search',
823 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
824 'title' => ts('Release Respondents'),
829 if (CRM_Core_Permission
::check('access CiviReport')) {
830 $reportID = self
::getReportID($surveyId);
832 $voterLinks['report'] = array(
834 'url' => "civicrm/report/instance/{$reportID}",
836 'title' => ts('View Survey Report'),
841 $ids = array('id' => $surveyId);
842 foreach ($voterLinks as $link) {
843 if (!empty($link['qs']) &&
844 !CRM_Utils_System
::isNull($link['qs'])
846 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
847 CRM_Core_Action
::replace($link['qs'], $ids)
849 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
851 CRM_Utils_Array
::value('title', $link),
857 $extraLinksName = strtolower($extraULName);
859 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
860 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
861 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
868 * Retrieve survey associated profile id.
870 * @param int $surveyId
874 public static function getSurveyProfileId($surveyId) {
879 static $ufIds = array();
880 if (!array_key_exists($surveyId, $ufIds)) {
881 //get the profile id.
882 $ufJoinParams = array(
883 'entity_id' => $surveyId,
884 'entity_table' => 'civicrm_survey',
885 'module' => 'CiviCampaign',
888 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
891 $ufIds[$surveyId] = array($first);
894 $ufIds[$surveyId][] = array_shift($second);
898 return CRM_Utils_Array
::value($surveyId, $ufIds);
902 * @param int $surveyId
906 public Static function getReportID($surveyId) {
907 static $reportIds = array();
909 if (!array_key_exists($surveyId, $reportIds)) {
910 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
911 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
912 $reportIds[$surveyId] = $reportID;
914 return $reportIds[$surveyId];
918 * Decides the contact type for given survey.
920 * @param int $surveyId
922 * @return null|string
924 public static function getSurveyContactType($surveyId) {
927 //apply filter of profile type on search.
928 $profileId = self
::getSurveyProfileId($surveyId);
930 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
931 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
932 $contactType = $profileType;
940 * Get survey supportable profile types.
942 public static function surveyProfileTypes() {
943 static $profileTypes;
945 if (!isset($profileTypes)) {
946 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
947 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
950 return $profileTypes;
954 * Get the valid survey response fields those.
955 * are configured with profile and custom fields.
957 * @param int $surveyId
959 * @param int $surveyTypeId
960 * Survey activity type id.
963 * an array of valid survey response fields.
965 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
966 if (empty($surveyId)) {
970 static $responseFields;
971 $cacheKey = "{$surveyId}_{$surveyTypeId}";
973 if (isset($responseFields[$cacheKey])) {
974 return $responseFields[$cacheKey];
977 $responseFields[$cacheKey] = array();
979 $profileId = self
::getSurveyProfileId($surveyId);
982 return $responseFields;
985 if (!$surveyTypeId) {
986 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
989 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
990 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
993 //don't load these fields in grid.
994 $removeFields = array('File', 'RichTextEditor');
996 $supportableFieldTypes = self
::surveyProfileTypes();
998 // get custom fields of type survey
999 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
1001 foreach ($profileFields as $name => $field) {
1002 //get only contact and activity fields.
1003 //later stage we might going to consider contact type also.
1004 if (in_array($field['field_type'], $supportableFieldTypes)) {
1005 // we should allow all supported custom data for survey
1006 // In case of activity, allow normal activity and with subtype survey,
1007 // suppress custom data of other activity types
1008 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1009 if (!in_array($field['html_type'], $removeFields)) {
1010 if ($field['field_type'] != 'Activity') {
1011 $responseFields[$cacheKey][$name] = $field;
1013 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1014 $responseFields[$cacheKey][$name] = $field;
1019 $responseFields[$cacheKey][$name] = $field;
1024 return $responseFields[$cacheKey];
1028 * Get all interviewers of surveys.
1031 * an array of valid survey response fields.
1033 public static function getInterviewers() {
1034 static $interviewers;
1036 if (isset($interviewers)) {
1037 return $interviewers;
1040 $whereClause = NULL;
1041 $activityTypes = self
::getSurveyActivityType();
1042 if (!empty($activityTypes)) {
1043 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1046 $interviewers = array();
1047 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1048 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1051 SELECT contact.id as id,
1052 contact.sort_name as sort_name
1053 FROM civicrm_contact contact
1054 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1055 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1056 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1059 $interviewer = CRM_Core_DAO
::executeQuery($query);
1060 while ($interviewer->fetch()) {
1061 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1064 return $interviewers;
1068 * Check and update the survey respondents.
1070 * @param array $params
1075 public static function releaseRespondent($params) {
1076 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1077 $reserveStatusId = array_search('Scheduled', $activityStatus);
1078 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1079 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1080 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1083 //retrieve all survey activities related to reserve action.
1085 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1087 SELECT activity.id as id,
1088 activity.activity_date_time as activity_date_time,
1089 survey.id as surveyId,
1090 survey.release_frequency as release_frequency
1091 FROM civicrm_activity activity
1092 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1093 WHERE activity.is_deleted = 0
1094 AND activity.status_id = %1
1095 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1096 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1097 $releasedIds = array();
1098 while ($activity->fetch()) {
1099 if (!$activity->release_frequency
) {
1102 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1103 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1104 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1105 if ($totalReservedSeconds < time()) {
1106 $releasedIds[$activity->id
] = $activity->id
;
1110 //released respondent.
1111 if (!empty($releasedIds)) {
1113 UPDATE civicrm_activity
1115 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1116 CRM_Core_DAO
::executeQuery($query);
1117 $releasedCount = count($releasedIds);
1123 'messages' => "Number of respondents released = {$releasedCount}",
1130 * Get options for a given field.
1131 * @see CRM_Core_DAO::buildOptions
1133 * @param string $fieldName
1134 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1135 * @param array $props : whatever is known about this dao object
1137 * @return array|bool
1139 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1141 // Special logic for fields whose options depend on context or properties
1142 switch ($fieldName) {
1143 case 'activity_type_id':
1144 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1145 if ($campaignCompId) {
1146 $params['condition'] = array("component_id={$campaignCompId}");
1150 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);