3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 based on the
67 * @param array $params
69 * @return bool|CRM_Campaign_DAO_Survey
71 public static function create(&$params) {
76 if (!empty($params['is_default'])) {
77 $query = "UPDATE civicrm_survey SET is_default = 0";
78 CRM_Core_DAO
::executeQuery($query);
81 if (!(CRM_Utils_Array
::value('id', $params))) {
83 if (!(CRM_Utils_Array
::value('created_id', $params))) {
84 $session = CRM_Core_Session
::singleton();
85 $params['created_id'] = $session->get('userID');
87 if (!(CRM_Utils_Array
::value('created_date', $params))) {
88 $params['created_date'] = date('YmdHis');
91 CRM_Utils_Hook
::pre('create', 'Survey', NULL, $params);
94 CRM_Utils_Hook
::pre('edit', 'Survey', $params['id'], $params);
97 $dao = new CRM_Campaign_DAO_Survey();
98 $dao->copyValues($params);
101 if (!empty($params['id'])) {
102 CRM_Utils_Hook
::post('edit', 'Survey', $dao->id
, $dao);
105 CRM_Utils_Hook
::post('create', 'Survey', $dao->id
, $dao);
108 if (!empty($params['custom']) &&
109 is_array($params['custom'])
111 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
117 * Retrieve surveys for dashboard.
119 * @param array $params
120 * @param bool $onlyCount
124 public static function getSurveySummary($params = array(), $onlyCount = FALSE) {
125 //build the limit and order clause.
126 $limitClause = $orderByClause = $lookupTableJoins = NULL;
129 'sort' => 'created_date',
132 'sortOrder' => 'desc',
134 foreach ($sortParams as $name => $default) {
135 if (!empty($params[$name])) {
136 $sortParams[$name] = $params[$name];
140 //need to lookup tables.
141 $orderOnSurveyTable = TRUE;
142 if ($sortParams['sort'] == 'campaign') {
143 $orderOnSurveyTable = FALSE;
144 $lookupTableJoins = '
145 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
146 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
148 elseif ($sortParams['sort'] == 'activity_type') {
149 $orderOnSurveyTable = FALSE;
150 $lookupTableJoins = "
151 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
152 OR survey.activity_type_id IS NULL )
153 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
154 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
156 elseif ($sortParams['sort'] == 'isActive') {
157 $sortParams['sort'] = 'is_active';
159 if ($orderOnSurveyTable) {
160 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
162 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
165 //build the where clause.
166 $queryParams = $where = array();
168 //we only have activity type as a
169 //difference between survey and petition.
170 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Petition');
171 if ($petitionTypeID) {
172 $where[] = "( survey.activity_type_id != %1 )";
173 $queryParams[1] = array($petitionTypeID, 'Positive');
176 if (!empty($params['title'])) {
177 $where[] = "( survey.title LIKE %2 )";
178 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
180 if (!empty($params['campaign_id'])) {
181 $where[] = '( survey.campaign_id = %3 )';
182 $queryParams[3] = array($params['campaign_id'], 'Positive');
184 if (!empty($params['activity_type_id'])) {
185 $typeId = $params['activity_type_id'];
186 if (is_array($params['activity_type_id'])) {
187 $typeId = implode(' , ', $params['activity_type_id']);
189 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
192 if (!empty($where)) {
193 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
197 SELECT survey.id as id,
198 survey.title as title,
199 survey.is_active as is_active,
200 survey.result_id as result_id,
201 survey.is_default as is_default,
202 survey.campaign_id as campaign_id,
203 survey.activity_type_id as activity_type_id,
204 survey.release_frequency as release_frequency,
205 survey.max_number_of_contacts as max_number_of_contacts,
206 survey.default_number_of_contacts as default_number_of_contacts';
208 $selectClause = 'SELECT COUNT(*)';
210 $fromClause = 'FROM civicrm_survey survey';
212 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
216 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
229 'max_number_of_contacts',
230 'default_number_of_contacts',
233 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
234 while ($survey->fetch()) {
235 foreach ($properties as $property) {
236 $surveys[$survey->id
][$property] = $survey->$property;
244 * Get the survey count.
247 public static function getSurveyCount() {
248 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
254 * @param bool $onlyActive
255 * Retrieve only active surveys.
256 * @param bool $onlyDefault
257 * Retrieve only default survey.
258 * @param bool $forceAll
259 * Retrieve all surveys.
260 * @param bool $includePetition
261 * Include or exclude petitions.
264 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
266 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
267 foreach ($cacheKeyParams as $param) {
268 $cacheParam = $
$param;
272 $cacheKey .= '_' . $cacheParam;
277 if (!isset($surveys[$cacheKey])) {
278 if (!$includePetition) {
279 //we only have activity type as a
280 //difference between survey and petition.
281 $petitionTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'petition');
284 if ($petitionTypeID) {
285 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
288 if (!$forceAll && $onlyActive) {
289 $where[] = '( survey.is_active = 1 )';
291 if (!$forceAll && $onlyDefault) {
292 $where[] = '( survey.is_default = 1 )';
294 $whereClause = implode(' AND ', $where);
297 SELECT survey.id as id,
298 survey.title as title
299 FROM civicrm_survey as survey
300 WHERE {$whereClause}";
301 $surveys[$cacheKey] = array();
302 $survey = CRM_Core_DAO
::executeQuery($query);
303 while ($survey->fetch()) {
304 $surveys[$cacheKey][$survey->id
] = $survey->title
;
308 return $surveys[$cacheKey];
312 * Get Survey activity types.
314 * @param string $returnColumn
315 * @param bool $includePetitionActivityType
319 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
320 static $activityTypes;
321 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
323 if (!isset($activityTypes[$cacheKey])) {
324 $activityTypes = array();
325 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
326 if ($campaignCompId) {
327 $condition = " AND v.component_id={$campaignCompId}";
328 if (!$includePetitionActivityType) {
329 $condition .= " AND v.name != 'Petition'";
331 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
338 if (!empty($activityTypes[$cacheKey])) {
339 return $activityTypes[$cacheKey];
347 * Get Surveys custom groups.
349 * @param array $surveyTypes
350 * an array of survey type id.
354 public static function getSurveyCustomGroups($surveyTypes = array()) {
355 $customGroups = array();
356 if (!is_array($surveyTypes)) {
357 $surveyTypes = array($surveyTypes);
360 if (!empty($surveyTypes)) {
361 $activityTypes = array_flip($surveyTypes);
364 $activityTypes = self
::getSurveyActivityType();
367 if (!empty($activityTypes)) {
368 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
370 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
371 FROM civicrm_custom_group cg
372 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
374 $dao = CRM_Core_DAO
::executeQuery($query);
375 while ($dao->fetch()) {
376 $customGroups[$dao->id
]['id'] = $dao->id
;
377 $customGroups[$dao->id
]['name'] = $dao->name
;
378 $customGroups[$dao->id
]['title'] = $dao->title
;
379 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
383 return $customGroups;
387 * Update the is_active flag in the db.
390 * Id of the database record.
391 * @param bool $is_active
392 * Value we want to set the is_active field.
395 * true if we found and updated the object, else false
397 public static function setIsActive($id, $is_active) {
398 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
409 public static function del($id) {
413 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
415 CRM_Report_BAO_ReportInstance
::del($reportId);
417 $dao = new CRM_Campaign_DAO_Survey();
419 return $dao->delete();
423 * This function retrieve contact information.
425 * @param array $voterIds
426 * @param array $returnProperties
427 * An array of return elements.
430 * array of contact info.
432 public static function voterDetails($voterIds, $returnProperties = array()) {
433 $voterDetails = array();
434 if (!is_array($voterIds) ||
empty($voterIds)) {
435 return $voterDetails;
438 if (empty($returnProperties)) {
439 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
440 'contact_autocomplete_options'
442 $returnProperties = array_fill_keys(array_merge(array(
447 array_keys($autocompleteContactSearch)
451 $select = $from = array();
452 foreach ($returnProperties as $property => $ignore) {
453 $value = (in_array($property, array(
456 ))) ?
'address' : $property;
460 case 'contact_sub_type':
461 $select[] = "$property as $property";
462 $from['contact'] = 'civicrm_contact contact';
468 case 'street_address':
469 $select[] = "$property as $property";
470 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
474 case 'state_province':
475 $select[] = "{$property}.name as $property";
476 if (!in_array('address', $from)) {
477 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
479 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
484 //finally retrieve contact details.
485 if (!empty($select) && !empty($from)) {
486 $fromClause = implode(' ', $from);
487 $selectClause = implode(', ', $select);
488 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
491 SELECT contact.id as contactId, $selectClause
495 $contact = CRM_Core_DAO
::executeQuery($query);
496 while ($contact->fetch()) {
497 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
498 foreach ($returnProperties as $property => $ignore) {
499 $voterDetails[$contact->contactId
][$property] = $contact->$property;
501 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
505 $voterDetails[$contact->contactId
]['contact_type'] = $image;
510 return $voterDetails;
514 * This function retrieve survey related activities w/ for give voter ids.
516 * @param int $surveyId
518 * @param array $voterIds
521 * @param int $interviewerId
522 * @param array $statusIds
525 * array of survey activity.
527 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = array()) {
528 $activityDetails = array();
530 !is_array($voterIds) ||
empty($voterIds)
532 return $activityDetails;
536 if (is_array($statusIds) && !empty($statusIds)) {
537 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
540 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
541 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
542 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
543 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
545 $params[1] = array($surveyId, 'Integer');
547 SELECT activity.id, activity.status_id,
548 activityTarget.contact_id as voter_id,
549 activityAssignment.contact_id as interviewer_id
550 FROM civicrm_activity activity
551 INNER JOIN civicrm_activity_contact activityTarget
552 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
553 INNER JOIN civicrm_activity_contact activityAssignment
554 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
555 WHERE activity.source_record_id = %1
556 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
557 if (!empty($interviewerId)) {
558 $query .= "AND activityAssignment.contact_id = %2 ";
559 $params[2] = array($interviewerId, 'Integer');
561 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
563 $activity = CRM_Core_DAO
::executeQuery($query, $params);
564 while ($activity->fetch()) {
565 $activityDetails[$activity->voter_id
] = array(
566 'voter_id' => $activity->voter_id
,
567 'status_id' => $activity->status_id
,
568 'activity_id' => $activity->id
,
569 'interviewer_id' => $activity->interviewer_id
,
573 return $activityDetails;
577 * This function retrieve survey related activities.
579 * @param int $surveyId
580 * @param int $interviewerId
581 * @param array $statusIds
582 * @param array $voterIds
583 * @param bool $onlyCount
586 * An array of survey activity.
588 public static function getSurveyActivities(
590 $interviewerId = NULL,
595 $activities = array();
596 $surveyActivityCount = 0;
598 return ($onlyCount) ?
0 : $activities;
602 if (!empty($statusIds)) {
603 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
606 if ($interviewerId) {
607 $where[] = "( activityAssignment.contact_id = $interviewerId )";
610 if (!empty($voterIds)) {
611 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
615 if (!empty($where)) {
616 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
619 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
625 $select = "SELECT count(activity.id)";
629 SELECT activity.id, activity.status_id,
630 activityTarget.contact_id as voter_id,
631 activityAssignment.contact_id as interviewer_id,
632 activity.result as result,
633 activity.activity_date_time as activity_date_time,
634 contact_a.display_name as voter_name";
637 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
638 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
639 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
643 FROM civicrm_activity activity
644 INNER JOIN civicrm_activity_contact activityTarget
645 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
646 INNER JOIN civicrm_activity_contact activityAssignment
647 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
648 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
649 WHERE activity.source_record_id = %1
650 AND activity.activity_type_id = %2
651 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
655 1 => array($surveyId, 'Integer'),
656 2 => array($actTypeId, 'Integer'),
660 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
661 return ($dbCount) ?
$dbCount : 0;
664 $activity = CRM_Core_DAO
::executeQuery($query, $params);
666 while ($activity->fetch()) {
667 $activities[$activity->id
] = array(
668 'id' => $activity->id
,
669 'voter_id' => $activity->voter_id
,
670 'voter_name' => $activity->voter_name
,
671 'status_id' => $activity->status_id
,
672 'interviewer_id' => $activity->interviewer_id
,
673 'result' => $activity->result
,
674 'activity_date_time' => $activity->activity_date_time
,
682 * Retrieve survey voter information.
684 * @param int $surveyId
686 * @param int $interviewerId
688 * @param array $statusIds
692 * Survey related contact ids.
694 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
700 $cacheKey = $surveyId;
701 if ($interviewerId) {
702 $cacheKey .= "_{$interviewerId}";
704 if (is_array($statusIds) && !empty($statusIds)) {
705 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
708 static $contactIds = array();
709 if (!isset($contactIds[$cacheKey])) {
710 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
711 foreach ($activities as $values) {
712 $voterIds[$values['voter_id']] = $values;
714 $contactIds[$cacheKey] = $voterIds;
717 return $contactIds[$cacheKey];
721 * This function retrieve all option groups which are created as a result set.
723 * @param string $valueColumnName
725 * an array of option groups.
727 public static function getResultSets($valueColumnName = 'title') {
728 $resultSets = array();
729 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
731 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
732 $dao = CRM_Core_DAO
::executeQuery($query);
733 while ($dao->fetch()) {
734 $resultSets[$dao->id
] = $dao->$valueColumnName;
741 * check survey activity.
743 * @param int $activityId
747 public static function isSurveyActivity($activityId) {
748 $isSurveyActivity = FALSE;
750 return $isSurveyActivity;
753 $activity = new CRM_Activity_DAO_Activity();
754 $activity->id
= $activityId;
755 $activity->selectAdd('source_record_id, activity_type_id');
756 if ($activity->find(TRUE) &&
757 $activity->source_record_id
759 $surveyActTypes = self
::getSurveyActivityType();
760 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
761 $isSurveyActivity = TRUE;
765 return $isSurveyActivity;
769 * This function retrive all response options of survey.
771 * @param int $surveyId
774 * an array of option values
776 public static function getResponsesOptions($surveyId) {
777 $responseOptions = array();
779 return $responseOptions;
782 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
784 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
787 return $responseOptions;
791 * This function return all voter links with respecting permissions.
793 * @param int $surveyId
794 * @param bool $enclosedInUL
795 * @param string $extraULName
796 * @return array|string
797 * $url array of permissioned links
799 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
800 $menuLinks = array();
805 static $voterLinks = array();
806 if (empty($voterLinks)) {
807 $permissioned = FALSE;
808 if (CRM_Core_Permission
::check('manage campaign') ||
809 CRM_Core_Permission
::check('administer CiviCampaign')
811 $permissioned = TRUE;
814 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
815 $voterLinks['reserve'] = array(
817 'url' => 'civicrm/survey/search',
818 'qs' => 'sid=%%id%%&reset=1&op=reserve',
819 'title' => ts('Reserve Respondents'),
822 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
823 $voterLinks['release'] = array(
824 'name' => 'interview',
825 'url' => 'civicrm/survey/search',
826 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
827 'title' => ts('Interview Respondents'),
830 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
831 $voterLinks['interview'] = array(
833 'url' => 'civicrm/survey/search',
834 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
835 'title' => ts('Release Respondents'),
840 if (CRM_Core_Permission
::check('access CiviReport')) {
841 $reportID = self
::getReportID($surveyId);
843 $voterLinks['report'] = array(
845 'url' => "civicrm/report/instance/{$reportID}",
847 'title' => ts('View Survey Report'),
852 $ids = array('id' => $surveyId);
853 foreach ($voterLinks as $link) {
854 if (!empty($link['qs']) &&
855 !CRM_Utils_System
::isNull($link['qs'])
857 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
858 CRM_Core_Action
::replace($link['qs'], $ids)
860 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
862 CRM_Utils_Array
::value('title', $link),
868 $extraLinksName = strtolower($extraULName);
870 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
871 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
872 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
879 * Retrieve survey associated profile id.
881 * @param int $surveyId
885 public static function getSurveyProfileId($surveyId) {
890 static $ufIds = array();
891 if (!array_key_exists($surveyId, $ufIds)) {
892 //get the profile id.
893 $ufJoinParams = array(
894 'entity_id' => $surveyId,
895 'entity_table' => 'civicrm_survey',
896 'module' => 'CiviCampaign',
899 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
902 $ufIds[$surveyId] = array($first);
905 $ufIds[$surveyId][] = array_shift($second);
909 return CRM_Utils_Array
::value($surveyId, $ufIds);
913 * @param int $surveyId
917 public Static function getReportID($surveyId) {
918 static $reportIds = array();
920 if (!array_key_exists($surveyId, $reportIds)) {
921 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
922 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
923 $reportIds[$surveyId] = $reportID;
925 return $reportIds[$surveyId];
929 * Decides the contact type for given survey.
931 * @param int $surveyId
933 * @return null|string
935 public static function getSurveyContactType($surveyId) {
938 //apply filter of profile type on search.
939 $profileId = self
::getSurveyProfileId($surveyId);
941 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
942 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
943 $contactType = $profileType;
951 * Get survey supportable profile types.
953 public static function surveyProfileTypes() {
954 static $profileTypes;
956 if (!isset($profileTypes)) {
957 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
958 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
961 return $profileTypes;
965 * Get the valid survey response fields those.
966 * are configured with profile and custom fields.
968 * @param int $surveyId
970 * @param int $surveyTypeId
971 * Survey activity type id.
974 * an array of valid survey response fields.
976 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
977 if (empty($surveyId)) {
981 static $responseFields;
982 $cacheKey = "{$surveyId}_{$surveyTypeId}";
984 if (isset($responseFields[$cacheKey])) {
985 return $responseFields[$cacheKey];
988 $responseFields[$cacheKey] = array();
990 $profileId = self
::getSurveyProfileId($surveyId);
993 return $responseFields;
996 if (!$surveyTypeId) {
997 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
1000 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
1001 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
1004 //don't load these fields in grid.
1005 $removeFields = array('File', 'RichTextEditor');
1007 $supportableFieldTypes = self
::surveyProfileTypes();
1009 // get custom fields of type survey
1010 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
1012 foreach ($profileFields as $name => $field) {
1013 //get only contact and activity fields.
1014 //later stage we might going to consider contact type also.
1015 if (in_array($field['field_type'], $supportableFieldTypes)) {
1016 // we should allow all supported custom data for survey
1017 // In case of activity, allow normal activity and with subtype survey,
1018 // suppress custom data of other activity types
1019 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1020 if (!in_array($field['html_type'], $removeFields)) {
1021 if ($field['field_type'] != 'Activity') {
1022 $responseFields[$cacheKey][$name] = $field;
1024 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1025 $responseFields[$cacheKey][$name] = $field;
1030 $responseFields[$cacheKey][$name] = $field;
1035 return $responseFields[$cacheKey];
1039 * Get all interviewers of surveys.
1042 * an array of valid survey response fields.
1044 public static function getInterviewers() {
1045 static $interviewers;
1047 if (isset($interviewers)) {
1048 return $interviewers;
1051 $whereClause = NULL;
1052 $activityTypes = self
::getSurveyActivityType();
1053 if (!empty($activityTypes)) {
1054 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1057 $interviewers = array();
1058 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1059 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1062 SELECT contact.id as id,
1063 contact.sort_name as sort_name
1064 FROM civicrm_contact contact
1065 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1066 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1067 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1070 $interviewer = CRM_Core_DAO
::executeQuery($query);
1071 while ($interviewer->fetch()) {
1072 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1075 return $interviewers;
1079 * Check and update the survey respondents.
1081 * @param array $params
1086 public static function releaseRespondent($params) {
1087 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1088 $reserveStatusId = array_search('Scheduled', $activityStatus);
1089 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1090 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1091 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1094 //retrieve all survey activities related to reserve action.
1096 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1098 SELECT activity.id as id,
1099 activity.activity_date_time as activity_date_time,
1100 survey.id as surveyId,
1101 survey.release_frequency as release_frequency
1102 FROM civicrm_activity activity
1103 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1104 WHERE activity.is_deleted = 0
1105 AND activity.status_id = %1
1106 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1107 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1108 $releasedIds = array();
1109 while ($activity->fetch()) {
1110 if (!$activity->release_frequency
) {
1113 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1114 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1115 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1116 if ($totalReservedSeconds < time()) {
1117 $releasedIds[$activity->id
] = $activity->id
;
1121 //released respondent.
1122 if (!empty($releasedIds)) {
1124 UPDATE civicrm_activity
1126 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1127 CRM_Core_DAO
::executeQuery($query);
1128 $releasedCount = count($releasedIds);
1134 'messages' => "Number of respondents released = {$releasedCount}",
1141 * Get options for a given field.
1142 * @see CRM_Core_DAO::buildOptions
1144 * @param string $fieldName
1145 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1146 * @param array $props : whatever is known about this dao object
1148 * @return array|bool
1150 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1152 // Special logic for fields whose options depend on context or properties
1153 switch ($fieldName) {
1154 case 'activity_type_id':
1155 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1156 if ($campaignCompId) {
1157 $params['condition'] = array("component_id={$campaignCompId}");
1161 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);