3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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
310 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
311 static $activityTypes;
312 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
314 if (!isset($activityTypes[$cacheKey])) {
315 $activityTypes = array();
316 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
317 if ($campaignCompId) {
318 $condition = " AND v.component_id={$campaignCompId}";
319 if (!$includePetitionActivityType) {
320 $condition .= " AND v.name != 'Petition'";
322 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
329 if (!empty($activityTypes[$cacheKey])) {
330 return $activityTypes[$cacheKey];
338 * Get Surveys custom groups.
340 * @param array $surveyTypes
341 * an array of survey type id.
345 public static function getSurveyCustomGroups($surveyTypes = array()) {
346 $customGroups = array();
347 if (!is_array($surveyTypes)) {
348 $surveyTypes = array($surveyTypes);
351 if (!empty($surveyTypes)) {
352 $activityTypes = array_flip($surveyTypes);
355 $activityTypes = self
::getSurveyActivityType();
358 if (!empty($activityTypes)) {
359 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
361 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
362 FROM civicrm_custom_group cg
363 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
365 $dao = CRM_Core_DAO
::executeQuery($query);
366 while ($dao->fetch()) {
367 $customGroups[$dao->id
]['id'] = $dao->id
;
368 $customGroups[$dao->id
]['name'] = $dao->name
;
369 $customGroups[$dao->id
]['title'] = $dao->title
;
370 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
374 return $customGroups;
378 * Update the is_active flag in the db.
381 * Id of the database record.
382 * @param bool $is_active
383 * Value we want to set the is_active field.
386 * DAO object on success, null otherwise
388 public static function setIsActive($id, $is_active) {
389 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
400 public static function del($id) {
404 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
406 CRM_Report_BAO_ReportInstance
::del($reportId);
408 $dao = new CRM_Campaign_DAO_Survey();
410 return $dao->delete();
414 * This function retrieve contact information.
416 * @param array $voterIds
417 * @param array $returnProperties
418 * An array of return elements.
421 * array of contact info.
423 public static function voterDetails($voterIds, $returnProperties = array()) {
424 $voterDetails = array();
425 if (!is_array($voterIds) ||
empty($voterIds)) {
426 return $voterDetails;
429 if (empty($returnProperties)) {
430 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
431 'contact_autocomplete_options'
433 $returnProperties = array_fill_keys(array_merge(array(
438 array_keys($autocompleteContactSearch)
442 $select = $from = array();
443 foreach ($returnProperties as $property => $ignore) {
444 $value = (in_array($property, array(
447 ))) ?
'address' : $property;
451 case 'contact_sub_type':
452 $select[] = "$property as $property";
453 $from['contact'] = 'civicrm_contact contact';
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 ) ";
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) ';
470 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
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) . ')';
482 SELECT contact.id as contactId, $selectClause
486 $contact = CRM_Core_DAO
::executeQuery($query);
487 while ($contact->fetch()) {
488 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
489 foreach ($returnProperties as $property => $ignore) {
490 $voterDetails[$contact->contactId
][$property] = $contact->$property;
492 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
496 $voterDetails[$contact->contactId
]['contact_type'] = $image;
501 return $voterDetails;
505 * This function retrieve survey related activities w/ for give voter ids.
507 * @param int $surveyId
509 * @param array $voterIds
512 * @param int $interviewerId
513 * @param array $statusIds
516 * array of survey activity.
518 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = array()) {
519 $activityDetails = array();
521 !is_array($voterIds) ||
empty($voterIds)
523 return $activityDetails;
527 if (is_array($statusIds) && !empty($statusIds)) {
528 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
531 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
532 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
533 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
534 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
536 $params[1] = array($surveyId, 'Integer');
538 SELECT activity.id, activity.status_id,
539 activityTarget.contact_id as voter_id,
540 activityAssignment.contact_id as interviewer_id
541 FROM civicrm_activity activity
542 INNER JOIN civicrm_activity_contact activityTarget
543 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
544 INNER JOIN civicrm_activity_contact activityAssignment
545 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
546 WHERE activity.source_record_id = %1
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');
552 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
554 $activity = CRM_Core_DAO
::executeQuery($query, $params);
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
,
564 return $activityDetails;
568 * This function retrieve survey related activities.
570 * @param int $surveyId
571 * @param int $interviewerId
572 * @param array $statusIds
573 * @param array $voterIds
574 * @param bool $onlyCount
577 * An array of survey activity.
579 public static function getSurveyActivities(
581 $interviewerId = NULL,
586 $activities = array();
587 $surveyActivityCount = 0;
589 return ($onlyCount) ?
0 : $activities;
593 if (!empty($statusIds)) {
594 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
597 if ($interviewerId) {
598 $where[] = "( activityAssignment.contact_id = $interviewerId )";
601 if (!empty($voterIds)) {
602 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
606 if (!empty($where)) {
607 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
610 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
616 $select = "SELECT count(activity.id)";
620 SELECT activity.id, activity.status_id,
621 activityTarget.contact_id as voter_id,
622 activityAssignment.contact_id as interviewer_id,
623 activity.result as result,
624 activity.activity_date_time as activity_date_time,
625 contact_a.display_name as voter_name";
628 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
629 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
630 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
634 FROM civicrm_activity activity
635 INNER JOIN civicrm_activity_contact activityTarget
636 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
637 INNER JOIN civicrm_activity_contact activityAssignment
638 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
639 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
640 WHERE activity.source_record_id = %1
641 AND activity.activity_type_id = %2
642 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
646 1 => array($surveyId, 'Integer'),
647 2 => array($actTypeId, 'Integer'),
651 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
652 return ($dbCount) ?
$dbCount : 0;
655 $activity = CRM_Core_DAO
::executeQuery($query, $params);
657 while ($activity->fetch()) {
658 $activities[$activity->id
] = array(
659 'id' => $activity->id
,
660 'voter_id' => $activity->voter_id
,
661 'voter_name' => $activity->voter_name
,
662 'status_id' => $activity->status_id
,
663 'interviewer_id' => $activity->interviewer_id
,
664 'result' => $activity->result
,
665 'activity_date_time' => $activity->activity_date_time
,
673 * Retrieve survey voter information.
675 * @param int $surveyId
677 * @param int $interviewerId
679 * @param array $statusIds
683 * Survey related contact ids.
685 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
691 $cacheKey = $surveyId;
692 if ($interviewerId) {
693 $cacheKey .= "_{$interviewerId}";
695 if (is_array($statusIds) && !empty($statusIds)) {
696 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
699 static $contactIds = array();
700 if (!isset($contactIds[$cacheKey])) {
701 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
702 foreach ($activities as $values) {
703 $voterIds[$values['voter_id']] = $values;
705 $contactIds[$cacheKey] = $voterIds;
708 return $contactIds[$cacheKey];
712 * This function retrieve all option groups which are created as a result set.
714 * @param string $valueColumnName
716 * an array of option groups.
718 public static function getResultSets($valueColumnName = 'title') {
719 $resultSets = array();
720 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
722 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
723 $dao = CRM_Core_DAO
::executeQuery($query);
724 while ($dao->fetch()) {
725 $resultSets[$dao->id
] = $dao->$valueColumnName;
732 * check survey activity.
734 * @param int $activityId
738 public static function isSurveyActivity($activityId) {
739 $isSurveyActivity = FALSE;
741 return $isSurveyActivity;
744 $activity = new CRM_Activity_DAO_Activity();
745 $activity->id
= $activityId;
746 $activity->selectAdd('source_record_id, activity_type_id');
747 if ($activity->find(TRUE) &&
748 $activity->source_record_id
750 $surveyActTypes = self
::getSurveyActivityType();
751 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
752 $isSurveyActivity = TRUE;
756 return $isSurveyActivity;
760 * This function retrive all response options of survey.
762 * @param int $surveyId
765 * an array of option values
767 public static function getResponsesOptions($surveyId) {
768 $responseOptions = array();
770 return $responseOptions;
773 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
775 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
778 return $responseOptions;
782 * This function return all voter links with respecting permissions.
784 * @param int $surveyId
785 * @param bool $enclosedInUL
786 * @param string $extraULName
787 * @return array|string
788 * $url array of permissioned links
790 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
791 $menuLinks = array();
796 static $voterLinks = array();
797 if (empty($voterLinks)) {
798 $permissioned = FALSE;
799 if (CRM_Core_Permission
::check('manage campaign') ||
800 CRM_Core_Permission
::check('administer CiviCampaign')
802 $permissioned = TRUE;
805 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
806 $voterLinks['reserve'] = array(
808 'url' => 'civicrm/survey/search',
809 'qs' => 'sid=%%id%%&reset=1&op=reserve',
810 'title' => ts('Reserve Respondents'),
813 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
814 $voterLinks['release'] = array(
815 'name' => 'interview',
816 'url' => 'civicrm/survey/search',
817 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
818 'title' => ts('Interview Respondents'),
821 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
822 $voterLinks['interview'] = array(
824 'url' => 'civicrm/survey/search',
825 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
826 'title' => ts('Release Respondents'),
831 if (CRM_Core_Permission
::check('access CiviReport')) {
832 $reportID = self
::getReportID($surveyId);
834 $voterLinks['report'] = array(
836 'url' => "civicrm/report/instance/{$reportID}",
838 'title' => ts('View Survey Report'),
843 $ids = array('id' => $surveyId);
844 foreach ($voterLinks as $link) {
845 if (!empty($link['qs']) &&
846 !CRM_Utils_System
::isNull($link['qs'])
848 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
849 CRM_Core_Action
::replace($link['qs'], $ids)
851 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
853 CRM_Utils_Array
::value('title', $link),
859 $extraLinksName = strtolower($extraULName);
861 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
862 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
863 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
870 * Retrieve survey associated profile id.
872 * @param int $surveyId
876 public static function getSurveyProfileId($surveyId) {
881 static $ufIds = array();
882 if (!array_key_exists($surveyId, $ufIds)) {
883 //get the profile id.
884 $ufJoinParams = array(
885 'entity_id' => $surveyId,
886 'entity_table' => 'civicrm_survey',
887 'module' => 'CiviCampaign',
890 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
893 $ufIds[$surveyId] = array($first);
896 $ufIds[$surveyId][] = array_shift($second);
900 return CRM_Utils_Array
::value($surveyId, $ufIds);
904 * @param int $surveyId
908 public Static function getReportID($surveyId) {
909 static $reportIds = array();
911 if (!array_key_exists($surveyId, $reportIds)) {
912 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
913 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
914 $reportIds[$surveyId] = $reportID;
916 return $reportIds[$surveyId];
920 * Decides the contact type for given survey.
922 * @param int $surveyId
924 * @return null|string
926 public static function getSurveyContactType($surveyId) {
929 //apply filter of profile type on search.
930 $profileId = self
::getSurveyProfileId($surveyId);
932 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
933 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
934 $contactType = $profileType;
942 * Get survey supportable profile types.
944 public static function surveyProfileTypes() {
945 static $profileTypes;
947 if (!isset($profileTypes)) {
948 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
949 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
952 return $profileTypes;
956 * Get the valid survey response fields those.
957 * are configured with profile and custom fields.
959 * @param int $surveyId
961 * @param int $surveyTypeId
962 * Survey activity type id.
965 * an array of valid survey response fields.
967 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
968 if (empty($surveyId)) {
972 static $responseFields;
973 $cacheKey = "{$surveyId}_{$surveyTypeId}";
975 if (isset($responseFields[$cacheKey])) {
976 return $responseFields[$cacheKey];
979 $responseFields[$cacheKey] = array();
981 $profileId = self
::getSurveyProfileId($surveyId);
984 return $responseFields;
987 if (!$surveyTypeId) {
988 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
991 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
992 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
995 //don't load these fields in grid.
996 $removeFields = array('File', 'RichTextEditor');
998 $supportableFieldTypes = self
::surveyProfileTypes();
1000 // get custom fields of type survey
1001 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
1003 foreach ($profileFields as $name => $field) {
1004 //get only contact and activity fields.
1005 //later stage we might going to consider contact type also.
1006 if (in_array($field['field_type'], $supportableFieldTypes)) {
1007 // we should allow all supported custom data for survey
1008 // In case of activity, allow normal activity and with subtype survey,
1009 // suppress custom data of other activity types
1010 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1011 if (!in_array($field['html_type'], $removeFields)) {
1012 if ($field['field_type'] != 'Activity') {
1013 $responseFields[$cacheKey][$name] = $field;
1015 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1016 $responseFields[$cacheKey][$name] = $field;
1021 $responseFields[$cacheKey][$name] = $field;
1026 return $responseFields[$cacheKey];
1030 * Get all interviewers of surveys.
1033 * an array of valid survey response fields.
1035 public static function getInterviewers() {
1036 static $interviewers;
1038 if (isset($interviewers)) {
1039 return $interviewers;
1042 $whereClause = NULL;
1043 $activityTypes = self
::getSurveyActivityType();
1044 if (!empty($activityTypes)) {
1045 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1048 $interviewers = array();
1049 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1050 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1053 SELECT contact.id as id,
1054 contact.sort_name as sort_name
1055 FROM civicrm_contact contact
1056 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1057 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1058 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1061 $interviewer = CRM_Core_DAO
::executeQuery($query);
1062 while ($interviewer->fetch()) {
1063 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1066 return $interviewers;
1070 * Check and update the survey respondents.
1072 * @param array $params
1077 public static function releaseRespondent($params) {
1078 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1079 $reserveStatusId = array_search('Scheduled', $activityStatus);
1080 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1081 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1082 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1085 //retrieve all survey activities related to reserve action.
1087 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1089 SELECT activity.id as id,
1090 activity.activity_date_time as activity_date_time,
1091 survey.id as surveyId,
1092 survey.release_frequency as release_frequency
1093 FROM civicrm_activity activity
1094 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1095 WHERE activity.is_deleted = 0
1096 AND activity.status_id = %1
1097 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1098 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1099 $releasedIds = array();
1100 while ($activity->fetch()) {
1101 if (!$activity->release_frequency
) {
1104 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1105 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1106 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1107 if ($totalReservedSeconds < time()) {
1108 $releasedIds[$activity->id
] = $activity->id
;
1112 //released respondent.
1113 if (!empty($releasedIds)) {
1115 UPDATE civicrm_activity
1117 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1118 CRM_Core_DAO
::executeQuery($query);
1119 $releasedCount = count($releasedIds);
1125 'messages' => "Number of respondents released = {$releasedCount}",
1132 * Get options for a given field.
1133 * @see CRM_Core_DAO::buildOptions
1135 * @param string $fieldName
1136 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1137 * @param array $props : whatever is known about this dao object
1139 * @return array|bool
1141 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1143 // Special logic for fields whose options depend on context or properties
1144 switch ($fieldName) {
1145 case 'activity_type_id':
1146 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1147 if ($campaignCompId) {
1148 $params['condition'] = array("component_id={$campaignCompId}");
1152 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);