3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 require_once 'CRM/Campaign/DAO/Survey.php';
38 * Class CRM_Campaign_BAO_Survey
40 class CRM_Campaign_BAO_Survey
extends CRM_Campaign_DAO_Survey
{
43 * Retrieve DB object based on input parameters.
45 * It also stores all the retrieved values in the default array.
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
52 * @return CRM_Campaign_DAO_Survey|null
54 public static function retrieve(&$params, &$defaults) {
55 $dao = new CRM_Campaign_DAO_Survey();
57 $dao->copyValues($params);
59 if ($dao->find(TRUE)) {
60 CRM_Core_DAO
::storeValues($dao, $defaults);
67 * Takes an associative array and creates a Survey object.
69 * the function extract all the params it needs to initialize the create a
73 * @param array $params
75 * @return CRM_Survey_DAO_Survey
77 public static function create(&$params) {
82 if (!empty($params['is_default'])) {
83 $query = "UPDATE civicrm_survey SET is_default = 0";
84 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
87 if (!(CRM_Utils_Array
::value('id', $params))) {
89 if (!(CRM_Utils_Array
::value('created_id', $params))) {
90 $session = CRM_Core_Session
::singleton();
91 $params['created_id'] = $session->get('userID');
93 if (!(CRM_Utils_Array
::value('created_date', $params))) {
94 $params['created_date'] = date('YmdHis');
98 $dao = new CRM_Campaign_DAO_Survey();
99 $dao->copyValues($params);
102 if (!empty($params['custom']) &&
103 is_array($params['custom'])
105 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
111 * Retrieve surveys for dashboard.
114 public static function getSurveySummary($params = array(), $onlyCount = FALSE) {
115 //build the limit and order clause.
116 $limitClause = $orderByClause = $lookupTableJoins = NULL;
119 'sort' => 'created_date',
122 'sortOrder' => 'desc',
124 foreach ($sortParams as $name => $default) {
125 if (!empty($params[$name])) {
126 $sortParams[$name] = $params[$name];
130 //need to lookup tables.
131 $orderOnSurveyTable = TRUE;
132 if ($sortParams['sort'] == 'campaign') {
133 $orderOnSurveyTable = FALSE;
134 $lookupTableJoins = '
135 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
136 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
138 elseif ($sortParams['sort'] == 'activity_type') {
139 $orderOnSurveyTable = FALSE;
140 $lookupTableJoins = "
141 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
142 OR survey.activity_type_id IS NULL )
143 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
144 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
146 elseif ($sortParams['sort'] == 'isActive') {
147 $sortParams['sort'] = 'is_active';
149 if ($orderOnSurveyTable) {
150 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
152 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
155 //build the where clause.
156 $queryParams = $where = array();
158 //we only have activity type as a
159 //difference between survey and petition.
160 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
161 if ($petitionTypeID) {
162 $where[] = "( survey.activity_type_id != %1 )";
163 $queryParams[1] = array($petitionTypeID, 'Positive');
166 if (!empty($params['title'])) {
167 $where[] = "( survey.title LIKE %2 )";
168 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
170 if (!empty($params['campaign_id'])) {
171 $where[] = '( survey.campaign_id = %3 )';
172 $queryParams[3] = array($params['campaign_id'], 'Positive');
174 if (!empty($params['activity_type_id'])) {
175 $typeId = $params['activity_type_id'];
176 if (is_array($params['activity_type_id'])) {
177 $typeId = implode(' , ', $params['activity_type_id']);
179 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
182 if (!empty($where)) {
183 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
187 SELECT survey.id as id,
188 survey.title as title,
189 survey.is_active as is_active,
190 survey.result_id as result_id,
191 survey.is_default as is_default,
192 survey.campaign_id as campaign_id,
193 survey.activity_type_id as activity_type_id,
194 survey.release_frequency as release_frequency,
195 survey.max_number_of_contacts as max_number_of_contacts,
196 survey.default_number_of_contacts as default_number_of_contacts';
198 $selectClause = 'SELECT COUNT(*)';
200 $fromClause = 'FROM civicrm_survey survey';
202 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
206 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
219 'max_number_of_contacts',
220 'default_number_of_contacts',
223 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
224 while ($survey->fetch()) {
225 foreach ($properties as $property) {
226 $surveys[$survey->id
][$property] = $survey->$property;
234 * Get the survey count.
237 public static function getSurveyCount() {
238 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
244 * @param bool $onlyActive
245 * Retrieve only active surveys.
246 * @param bool $onlyDefault
247 * Retrieve only default survey.
248 * @param bool $forceAll
249 * Retrieve all surveys.
250 * @param bool $includePetition
251 * Include or exclude petitions.
254 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
256 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
257 foreach ($cacheKeyParams as $param) {
258 $cacheParam = $
$param;
262 $cacheKey .= '_' . $cacheParam;
267 if (!isset($surveys[$cacheKey])) {
268 if (!$includePetition) {
269 //we only have activity type as a
270 //difference between survey and petition.
271 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
274 if ($petitionTypeID) {
275 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
278 if (!$forceAll && $onlyActive) {
279 $where[] = '( survey.is_active = 1 )';
281 if (!$forceAll && $onlyDefault) {
282 $where[] = '( survey.is_default = 1 )';
284 $whereClause = implode(' AND ', $where);
287 SELECT survey.id as id,
288 survey.title as title
289 FROM civicrm_survey as survey
290 WHERE {$whereClause}";
291 $surveys[$cacheKey] = array();
292 $survey = CRM_Core_DAO
::executeQuery($query);
293 while ($survey->fetch()) {
294 $surveys[$cacheKey][$survey->id
] = $survey->title
;
298 return $surveys[$cacheKey];
302 * Get Survey activity types.
304 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
305 static $activityTypes;
306 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
308 if (!isset($activityTypes[$cacheKey])) {
309 $activityTypes = array();
310 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
311 if ($campaignCompId) {
312 $condition = " AND v.component_id={$campaignCompId}";
313 if (!$includePetitionActivityType) {
314 $condition .= " AND v.name != 'Petition'";
316 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
323 if (!empty($activityTypes[$cacheKey])) {
324 return $activityTypes[$cacheKey];
332 * Get Surveys custom groups.
334 * @param array $surveyTypes
335 * an array of survey type id.
339 public static function getSurveyCustomGroups($surveyTypes = array()) {
340 $customGroups = array();
341 if (!is_array($surveyTypes)) {
342 $surveyTypes = array($surveyTypes);
345 if (!empty($surveyTypes)) {
346 $activityTypes = array_flip($surveyTypes);
349 $activityTypes = self
::getSurveyActivityType();
352 if (!empty($activityTypes)) {
353 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
355 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
356 FROM civicrm_custom_group cg
357 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
359 $dao = CRM_Core_DAO
::executeQuery($query);
360 while ($dao->fetch()) {
361 $customGroups[$dao->id
]['id'] = $dao->id
;
362 $customGroups[$dao->id
]['name'] = $dao->name
;
363 $customGroups[$dao->id
]['title'] = $dao->title
;
364 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
368 return $customGroups;
372 * Update the is_active flag in the db.
375 * Id of the database record.
376 * @param bool $is_active
377 * Value we want to set the is_active field.
380 * DAO object on success, null otherwise
382 public static function setIsActive($id, $is_active) {
383 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
394 public static function del($id) {
398 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
400 CRM_Report_BAO_ReportInstance
::del($reportId);
402 $dao = new CRM_Campaign_DAO_Survey();
404 return $dao->delete();
408 * This function retrieve contact information.
410 * @param array $voterIds
411 * @param array $returnProperties
412 * An array of return elements.
415 * array of contact info.
417 public static function voterDetails($voterIds, $returnProperties = array()) {
418 $voterDetails = array();
419 if (!is_array($voterIds) ||
empty($voterIds)) {
420 return $voterDetails;
423 if (empty($returnProperties)) {
424 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
425 'contact_autocomplete_options'
427 $returnProperties = array_fill_keys(array_merge(array(
432 array_keys($autocompleteContactSearch)
436 $select = $from = array();
437 foreach ($returnProperties as $property => $ignore) {
438 $value = (in_array($property, array(
441 ))) ?
'address' : $property;
445 case 'contact_sub_type':
446 $select[] = "$property as $property";
447 $from['contact'] = 'civicrm_contact contact';
453 case 'street_address':
454 $select[] = "$property as $property";
455 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
459 case 'state_province':
460 $select[] = "{$property}.name as $property";
461 if (!in_array('address', $from)) {
462 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
464 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
469 //finally retrieve contact details.
470 if (!empty($select) && !empty($from)) {
471 $fromClause = implode(' ', $from);
472 $selectClause = implode(', ', $select);
473 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
476 SELECT contact.id as contactId, $selectClause
479 Group By contact.id";
481 $contact = CRM_Core_DAO
::executeQuery($query);
482 while ($contact->fetch()) {
483 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
484 foreach ($returnProperties as $property => $ignore) {
485 $voterDetails[$contact->contactId
][$property] = $contact->$property;
487 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
491 $voterDetails[$contact->contactId
]['contact_type'] = $image;
496 return $voterDetails;
500 * This function retrieve survey related activities w/ for give voter ids.
502 * @param int $surveyId
504 * @param array $voterIds
507 * @param int $interviewerId
508 * @param array $statusIds
511 * array of survey activity.
513 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = array()) {
514 $activityDetails = array();
516 !is_array($voterIds) ||
empty($voterIds)
518 return $activityDetails;
522 if (is_array($statusIds) && !empty($statusIds)) {
523 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
526 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
527 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
528 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
529 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
531 $params[1] = array($surveyId, 'Integer');
533 SELECT activity.id, activity.status_id,
534 activityTarget.contact_id as voter_id,
535 activityAssignment.contact_id as interviewer_id
536 FROM civicrm_activity activity
537 INNER JOIN civicrm_activity_contact activityTarget
538 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
539 INNER JOIN civicrm_activity_contact activityAssignment
540 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
541 WHERE activity.source_record_id = %1
542 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
543 if (!empty($interviewerId)) {
544 $query .= "AND activityAssignment.contact_id = %2 ";
545 $params[2] = array($interviewerId, 'Integer');
547 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
549 $activity = CRM_Core_DAO
::executeQuery($query, $params);
550 while ($activity->fetch()) {
551 $activityDetails[$activity->voter_id
] = array(
552 'voter_id' => $activity->voter_id
,
553 'status_id' => $activity->status_id
,
554 'activity_id' => $activity->id
,
555 'interviewer_id' => $activity->interviewer_id
,
559 return $activityDetails;
563 * This function retrieve survey related activities.
565 * @param int $surveyId
566 * @param int $interviewerId
567 * @param array $statusIds
568 * @param array $voterIds
569 * @param bool $onlyCount
572 * An array of survey activity.
574 public static function getSurveyActivities(
576 $interviewerId = NULL,
581 $activities = array();
582 $surveyActivityCount = 0;
584 return ($onlyCount) ?
0 : $activities;
588 if (!empty($statusIds)) {
589 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
592 if ($interviewerId) {
593 $where[] = "( activityAssignment.contact_id = $interviewerId )";
596 if (!empty($voterIds)) {
597 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
601 if (!empty($where)) {
602 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
605 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
611 $select = "SELECT count(activity.id)";
615 SELECT activity.id, activity.status_id,
616 activityTarget.contact_id as voter_id,
617 activityAssignment.contact_id as interviewer_id,
618 activity.result as result,
619 activity.activity_date_time as activity_date_time,
620 contact_a.display_name as voter_name";
623 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
624 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
625 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
629 FROM civicrm_activity activity
630 INNER JOIN civicrm_activity_contact activityTarget
631 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
632 INNER JOIN civicrm_activity_contact activityAssignment
633 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
634 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
635 WHERE activity.source_record_id = %1
636 AND activity.activity_type_id = %2
637 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
641 1 => array($surveyId, 'Integer'),
642 2 => array($actTypeId, 'Integer'),
646 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
647 return ($dbCount) ?
$dbCount : 0;
650 $activity = CRM_Core_DAO
::executeQuery($query, $params);
652 while ($activity->fetch()) {
653 $activities[$activity->id
] = array(
654 'id' => $activity->id
,
655 'voter_id' => $activity->voter_id
,
656 'voter_name' => $activity->voter_name
,
657 'status_id' => $activity->status_id
,
658 'interviewer_id' => $activity->interviewer_id
,
659 'result' => $activity->result
,
660 'activity_date_time' => $activity->activity_date_time
,
668 * Retrieve survey voter information.
670 * @param int $surveyId
672 * @param int $interviewerId
674 * @param array $statusIds
678 * Survey related contact ids.
680 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
686 $cacheKey = $surveyId;
687 if ($interviewerId) {
688 $cacheKey .= "_{$interviewerId}";
690 if (is_array($statusIds) && !empty($statusIds)) {
691 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
694 static $contactIds = array();
695 if (!isset($contactIds[$cacheKey])) {
696 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
697 foreach ($activities as $values) {
698 $voterIds[$values['voter_id']] = $values;
700 $contactIds[$cacheKey] = $voterIds;
703 return $contactIds[$cacheKey];
707 * This function retrieve all option groups which are created as a result set.
709 * @param string $valueColumnName
711 * an array of option groups.
713 public static function getResultSets($valueColumnName = 'title') {
714 $resultSets = array();
715 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
717 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
718 $dao = CRM_Core_DAO
::executeQuery($query);
719 while ($dao->fetch()) {
720 $resultSets[$dao->id
] = $dao->$valueColumnName;
727 * check survey activity.
729 * @param int $activityId
733 public static function isSurveyActivity($activityId) {
734 $isSurveyActivity = FALSE;
736 return $isSurveyActivity;
739 $activity = new CRM_Activity_DAO_Activity();
740 $activity->id
= $activityId;
741 $activity->selectAdd('source_record_id, activity_type_id');
742 if ($activity->find(TRUE) &&
743 $activity->source_record_id
745 $surveyActTypes = self
::getSurveyActivityType();
746 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
747 $isSurveyActivity = TRUE;
751 return $isSurveyActivity;
755 * This function retrive all response options of survey.
757 * @param int $surveyId
760 * an array of option values
762 public static function getResponsesOptions($surveyId) {
763 $responseOptions = array();
765 return $responseOptions;
768 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
770 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
773 return $responseOptions;
777 * This function return all voter links with respecting permissions.
779 * @param int $surveyId
780 * @param bool $enclosedInUL
781 * @param string $extraULName
782 * @return array|string
783 * $url array of permissioned links
785 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
786 $menuLinks = array();
791 static $voterLinks = array();
792 if (empty($voterLinks)) {
793 $permissioned = FALSE;
794 if (CRM_Core_Permission
::check('manage campaign') ||
795 CRM_Core_Permission
::check('administer CiviCampaign')
797 $permissioned = TRUE;
800 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
801 $voterLinks['reserve'] = array(
803 'url' => 'civicrm/survey/search',
804 'qs' => 'sid=%%id%%&reset=1&op=reserve',
805 'title' => ts('Reserve Respondents'),
808 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
809 $voterLinks['release'] = array(
810 'name' => 'interview',
811 'url' => 'civicrm/survey/search',
812 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
813 'title' => ts('Interview Respondents'),
816 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
817 $voterLinks['interview'] = array(
819 'url' => 'civicrm/survey/search',
820 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
821 'title' => ts('Release Respondents'),
826 if (CRM_Core_Permission
::check('access CiviReport')) {
827 $reportID = self
::getReportID($surveyId);
829 $voterLinks['report'] = array(
831 'url' => "civicrm/report/instance/{$reportID}",
833 'title' => ts('View Survey Report'),
838 $ids = array('id' => $surveyId);
839 foreach ($voterLinks as $link) {
840 if (!empty($link['qs']) &&
841 !CRM_Utils_System
::isNull($link['qs'])
843 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
844 CRM_Core_Action
::replace($link['qs'], $ids)
846 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
848 CRM_Utils_Array
::value('title', $link),
854 $extraLinksName = strtolower($extraULName);
856 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
857 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
858 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
865 * Retrieve survey associated profile id.
867 public static function getSurveyProfileId($surveyId) {
872 static $ufIds = array();
873 if (!array_key_exists($surveyId, $ufIds)) {
874 //get the profile id.
875 $ufJoinParams = array(
876 'entity_id' => $surveyId,
877 'entity_table' => 'civicrm_survey',
878 'module' => 'CiviCampaign',
881 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
884 $ufIds[$surveyId] = array($first);
887 $ufIds[$surveyId][] = array_shift($second);
891 return CRM_Utils_Array
::value($surveyId, $ufIds);
895 * @param int $surveyId
899 public Static function getReportID($surveyId) {
900 static $reportIds = array();
902 if (!array_key_exists($surveyId, $reportIds)) {
903 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
904 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
905 $reportIds[$surveyId] = $reportID;
907 return $reportIds[$surveyId];
911 * Decides the contact type for given survey.
913 public static function getSurveyContactType($surveyId) {
916 //apply filter of profile type on search.
917 $profileId = self
::getSurveyProfileId($surveyId);
919 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
920 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
921 $contactType = $profileType;
929 * Get survey supportable profile types.
931 public static function surveyProfileTypes() {
932 static $profileTypes;
934 if (!isset($profileTypes)) {
935 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
936 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
939 return $profileTypes;
943 * Get the valid survey response fields those.
944 * are configured with profile and custom fields.
946 * @param int $surveyId
948 * @param int $surveyTypeId
949 * Survey activity type id.
952 * an array of valid survey response fields.
954 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
955 if (empty($surveyId)) {
959 static $responseFields;
960 $cacheKey = "{$surveyId}_{$surveyTypeId}";
962 if (isset($responseFields[$cacheKey])) {
963 return $responseFields[$cacheKey];
966 $responseFields[$cacheKey] = array();
968 $profileId = self
::getSurveyProfileId($surveyId);
971 return $responseFields;
974 if (!$surveyTypeId) {
975 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
978 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
979 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
982 //don't load these fields in grid.
983 $removeFields = array('File', 'RichTextEditor');
985 $supportableFieldTypes = self
::surveyProfileTypes();
987 // get custom fields of type survey
988 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
990 foreach ($profileFields as $name => $field) {
991 //get only contact and activity fields.
992 //later stage we might going to consider contact type also.
993 if (in_array($field['field_type'], $supportableFieldTypes)) {
994 // we should allow all supported custom data for survey
995 // In case of activity, allow normal activity and with subtype survey,
996 // suppress custom data of other activity types
997 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
998 if (!in_array($field['html_type'], $removeFields)) {
999 if ($field['field_type'] != 'Activity') {
1000 $responseFields[$cacheKey][$name] = $field;
1002 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1003 $responseFields[$cacheKey][$name] = $field;
1008 $responseFields[$cacheKey][$name] = $field;
1013 return $responseFields[$cacheKey];
1017 * Get all interviewers of surveys.
1020 * an array of valid survey response fields.
1022 public static function getInterviewers() {
1023 static $interviewers;
1025 if (isset($interviewers)) {
1026 return $interviewers;
1029 $whereClause = NULL;
1030 $activityTypes = self
::getSurveyActivityType();
1031 if (!empty($activityTypes)) {
1032 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1035 $interviewers = array();
1036 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1037 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1040 SELECT contact.id as id,
1041 contact.sort_name as sort_name
1042 FROM civicrm_contact contact
1043 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1044 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1045 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1048 $interviewer = CRM_Core_DAO
::executeQuery($query);
1049 while ($interviewer->fetch()) {
1050 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1053 return $interviewers;
1057 * Check and update the survey respondents.
1059 * @param array $params
1064 public static function releaseRespondent($params) {
1065 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1066 $reserveStatusId = array_search('Scheduled', $activityStatus);
1067 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1068 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1069 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1072 //retrieve all survey activities related to reserve action.
1074 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1076 SELECT activity.id as id,
1077 activity.activity_date_time as activity_date_time,
1078 survey.id as surveyId,
1079 survey.release_frequency as release_frequency
1080 FROM civicrm_activity activity
1081 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1082 WHERE activity.is_deleted = 0
1083 AND activity.status_id = %1
1084 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1085 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1086 $releasedIds = array();
1087 while ($activity->fetch()) {
1088 if (!$activity->release_frequency
) {
1091 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1092 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1093 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1094 if ($totalReservedSeconds < time()) {
1095 $releasedIds[$activity->id
] = $activity->id
;
1099 //released respondent.
1100 if (!empty($releasedIds)) {
1102 UPDATE civicrm_activity
1104 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1105 CRM_Core_DAO
::executeQuery($query);
1106 $releasedCount = count($releasedIds);
1112 'messages' => "Number of respondents released = {$releasedCount}",
1119 * Get options for a given field.
1120 * @see CRM_Core_DAO::buildOptions
1122 * @param string $fieldName
1123 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1124 * @param array $props : whatever is known about this dao object
1126 * @return array|bool
1128 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1130 // Special logic for fields whose options depend on context or properties
1131 switch ($fieldName) {
1132 case 'activity_type_id':
1133 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1134 if ($campaignCompId) {
1135 $params['condition'] = array("component_id={$campaignCompId}");
1139 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);