3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 require_once 'CRM/Campaign/DAO/Survey.php';
36 class CRM_Campaign_BAO_Survey
extends CRM_Campaign_DAO_Survey
{
39 * Takes a bunch of params that are needed to match certain criteria and
40 * retrieves the relevant objects. Typically the valid params are only
43 * @param array $params (reference ) an assoc array of name/value pairs
44 * @param array $defaults (reference ) an assoc array to hold the flattened values
50 * The action links that we need to display for the browse screen
54 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 * @return object CRM_Survey_DAO_Survey object
77 static function create(&$params) {
82 if (CRM_Utils_Array
::value('is_default', $params)) {
83 $query = "UPDATE civicrm_survey SET is_default = 0";
84 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
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 (CRM_Utils_Array
::value('custom', $params) &&
103 is_array($params['custom'])
105 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
111 * Function to retrieve surveys for dashboard.
115 static function getSurveySummary($params = array(
116 ), $onlyCount = FALSE) {
117 //build the limit and order clause.
118 $limitClause = $orderByClause = $lookupTableJoins = NULL;
121 'sort' => 'created_date',
124 'sortOrder' => 'desc',
126 foreach ($sortParams as $name => $default) {
127 if (CRM_Utils_Array
::value($name, $params)) {
128 $sortParams[$name] = $params[$name];
132 //need to lookup tables.
133 $orderOnSurveyTable = TRUE;
134 if ($sortParams['sort'] == 'campaign') {
135 $orderOnSurveyTable = FALSE;
136 $lookupTableJoins = '
137 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
138 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
140 elseif ($sortParams['sort'] == 'activity_type') {
141 $orderOnSurveyTable = FALSE;
142 $lookupTableJoins = "
143 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
144 OR survey.activity_type_id IS NULL )
145 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
146 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
148 elseif ($sortParams['sort'] == 'isActive') {
149 $sortParams['sort'] = 'is_active';
151 if ($orderOnSurveyTable) {
152 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
154 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
157 //build the where clause.
158 $queryParams = $where = array();
160 //we only have activity type as a
161 //difference between survey and petition.
162 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
163 if ($petitionTypeID) {
164 $where[] = "( survey.activity_type_id != %1 )";
165 $queryParams[1] = array($petitionTypeID, 'Positive');
168 if (CRM_Utils_Array
::value('title', $params)) {
169 $where[] = "( survey.title LIKE %2 )";
170 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
172 if (CRM_Utils_Array
::value('campaign_id', $params)) {
173 $where[] = '( survey.campaign_id = %3 )';
174 $queryParams[3] = array($params['campaign_id'], 'Positive');
176 if (CRM_Utils_Array
::value('activity_type_id', $params)) {
177 $typeId = $params['activity_type_id'];
178 if (is_array($params['activity_type_id'])) {
179 $typeId = implode(' , ', $params['activity_type_id']);
181 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
184 if (!empty($where)) {
185 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
189 SELECT survey.id as id,
190 survey.title as title,
191 survey.is_active as is_active,
192 survey.result_id as result_id,
193 survey.is_default as is_default,
194 survey.campaign_id as campaign_id,
195 survey.activity_type_id as activity_type_id,
196 survey.release_frequency as release_frequency,
197 survey.max_number_of_contacts as max_number_of_contacts,
198 survey.default_number_of_contacts as default_number_of_contacts';
200 $selectClause = 'SELECT COUNT(*)';
202 $fromClause = 'FROM civicrm_survey survey';
204 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
208 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
213 'id', 'title', 'campaign_id', 'is_active', 'is_default', 'result_id', 'activity_type_id',
214 'release_frequency', 'max_number_of_contacts', 'default_number_of_contacts',
217 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
218 while ($survey->fetch()) {
219 foreach ($properties as $property) {
220 $surveys[$survey->id
][$property] = $survey->$property;
228 * Get the survey count.
232 static function getSurveyCount() {
233 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
237 * Function to get Surveys
239 * @param boolean $onlyActive retrieve only active surveys.
240 * @param boolean $onlyDefault retrieve only default survey.
241 * @param boolean $forceAll retrieve all surveys.
242 * @param boolean $includePetition include or exclude petitions
246 static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE ) {
248 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
249 foreach ($cacheKeyParams as $param) {
250 $cacheParam = $
$param;
254 $cacheKey .= '_' . $cacheParam;
259 if (!isset($surveys[$cacheKey])) {
260 if (!$includePetition) {
261 //we only have activity type as a
262 //difference between survey and petition.
263 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
266 if ($petitionTypeID) {
267 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
270 if (!$forceAll && $onlyActive) {
271 $where[] = '( survey.is_active = 1 )';
273 if (!$forceAll && $onlyDefault) {
274 $where[] = '( survey.is_default = 1 )';
276 $whereClause = implode(' AND ', $where);
279 SELECT survey.id as id,
280 survey.title as title
281 FROM civicrm_survey as survey
282 WHERE {$whereClause}";
283 $surveys[$cacheKey] = array();
284 $survey = CRM_Core_DAO
::executeQuery($query);
285 while ($survey->fetch()) {
286 $surveys[$cacheKey][$survey->id
] = $survey->title
;
290 return $surveys[$cacheKey];
294 * Function to get Surveys activity types
299 static function getSurveyActivityType($returnColumn = 'label',
300 $includePetitionActivityType = FALSE
302 static $activityTypes;
303 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
305 if (!isset($activityTypes[$cacheKey])) {
306 $activityTypes = array();
307 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
308 if ($campaignCompId) {
309 $condition = " AND v.component_id={$campaignCompId}";
310 if (!$includePetitionActivityType) {
311 $condition .= " AND v.name != 'Petition'";
313 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
321 return $activityTypes[$cacheKey];
325 * Function to get Surveys custom groups
327 * @param $surveyTypes array an array of survey type id.
331 static function getSurveyCustomGroups($surveyTypes = array(
333 $customGroups = array();
334 if (!is_array($surveyTypes)) {
335 $surveyTypes = array($surveyTypes);
338 if (!empty($surveyTypes)) {
339 $activityTypes = array_flip($surveyTypes);
342 $activityTypes = self
::getSurveyActivityType();
345 if (!empty($activityTypes)) {
346 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
348 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
349 FROM civicrm_custom_group cg
350 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
352 $dao = CRM_Core_DAO
::executeQuery($query);
353 while ($dao->fetch()) {
354 $customGroups[$dao->id
]['id'] = $dao->id
;
355 $customGroups[$dao->id
]['name'] = $dao->name
;
356 $customGroups[$dao->id
]['title'] = $dao->title
;
357 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
361 return $customGroups;
365 * update the is_active flag in the db
367 * @param int $id id of the database record
368 * @param boolean $is_active value we want to set the is_active field
370 * @return Object DAO object on sucess, null otherwise
373 static function setIsActive($id, $is_active) {
374 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
378 * Function to delete the survey
380 * @param int $id survey id
386 static function del($id) {
390 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
392 CRM_Report_BAO_ReportInstance
::del($reportId);
394 $dao = new CRM_Campaign_DAO_Survey();
396 return $dao->delete();
400 * This function retrieve contact information.
402 * @param array $voter an array of contact Ids.
403 * @param array $returnProperties an array of return elements.
405 * @return $voterDetails array of contact info.
408 static function voterDetails($voterIds, $returnProperties = array(
410 $voterDetails = array();
411 if (!is_array($voterIds) ||
empty($voterIds)) {
412 return $voterDetails;
415 if (empty($returnProperties)) {
416 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
417 'contact_autocomplete_options'
419 $returnProperties = array_fill_keys(array_merge(array(
424 array_keys($autocompleteContactSearch)
428 $select = $from = array();
429 foreach ($returnProperties as $property => $ignore) {
430 $value = (in_array($property, array(
431 'city', 'street_address'))) ?
'address' : $property;
435 case 'contact_sub_type':
436 $select[] = "$property as $property";
437 $from['contact'] = 'civicrm_contact contact';
443 case 'street_address':
444 $select[] = "$property as $property";
445 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
449 case 'state_province':
450 $select[] = "{$property}.name as $property";
451 if (!in_array('address', $from)) {
452 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
454 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
459 //finally retrieve contact details.
460 if (!empty($select) && !empty($from)) {
461 $fromClause = implode(' ', $from);
462 $selectClause = implode(', ', $select);
463 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
466 SELECT contact.id as contactId, $selectClause
469 Group By contact.id";
471 $contact = CRM_Core_DAO
::executeQuery($query);
472 while ($contact->fetch()) {
473 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
474 foreach ($returnProperties as $property => $ignore) {
475 $voterDetails[$contact->contactId
][$property] = $contact->$property;
477 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
478 $contact->contact_sub_type
: $contact->contact_type
,
482 $voterDetails[$contact->contactId
]['contact_type'] = $image;
487 return $voterDetails;
491 * This function retrieve survey related activities w/ for give voter ids.
493 * @param int $surveyId survey id.
494 * @param array $voterIds voterIds.
496 * @return $activityDetails array of survey activity.
499 static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL,
500 $statusIds = array()) {
501 $activityDetails = array();
503 !is_array($voterIds) ||
empty($voterIds)
505 return $activityDetails;
509 if (is_array($statusIds) && !empty($statusIds)) {
510 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
513 if (!$interviewerId) {
514 $session = CRM_Core_Session
::singleton();
515 $interviewerId = $session->get('userID');
518 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
519 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
520 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
521 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
524 SELECT activity.id, activity.status_id,
525 activityTarget.contact_id as voter_id,
526 activityAssignment.contact_id as interviewer_id
527 FROM civicrm_activity activity
528 INNER JOIN civicrm_activity_contact activityTarget
529 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
530 INNER JOIN civicrm_activity_contact activityAssignment
531 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
532 WHERE activity.source_record_id = %1
533 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
534 AND activityAssignment.contact_id = %2
535 AND activityTarget.contact_id IN {$targetContactIds}
538 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($surveyId, 'Integer'),
539 2 => array($interviewerId, 'Integer'),
541 while ($activity->fetch()) {
542 $activityDetails[$activity->voter_id
] = array(
543 'voter_id' => $activity->voter_id
,
544 'status_id' => $activity->status_id
,
545 'activity_id' => $activity->id
,
546 'interviewer_id' => $activity->interviewer_id
,
550 return $activityDetails;
554 * This function retrieve survey related activities.
556 * @param int $surveyId survey id.
558 * @return $activities an array of survey activity.
561 static function getSurveyActivities($surveyId,
562 $interviewerId = NULL,
567 $activities = array();
568 $surveyActivityCount = 0;
570 return ($onlyCount) ?
0 : $activities;
574 if (!empty($statusIds)) {
575 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
578 if ($interviewerId) {
579 $where[] = "( activityAssignment.contact_id = $interviewerId )";
582 if (!empty($voterIds)) {
583 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
587 if (!empty($where)) {
588 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
591 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
597 $select = "SELECT count(activity.id)";
601 SELECT activity.id, activity.status_id,
602 activityTarget.contact_id as voter_id,
603 activityAssignment.contact_id as interviewer_id,
604 activity.result as result,
605 activity.activity_date_time as activity_date_time,
606 contact_a.display_name as voter_name";
609 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
610 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
611 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
615 FROM civicrm_activity activity
616 INNER JOIN civicrm_activity_contact activityTarget
617 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
618 INNER JOIN civicrm_activity_contact activityAssignment
619 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
620 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
621 WHERE activity.source_record_id = %1
622 AND activity.activity_type_id = %2
623 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
626 $params = array(1 => array($surveyId, 'Integer'),
627 2 => array($actTypeId, 'Integer'),
631 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
632 return ($dbCount) ?
$dbCount : 0;
635 $activity = CRM_Core_DAO
::executeQuery($query, $params);
637 while ($activity->fetch()) {
638 $activities[$activity->id
] = array(
639 'id' => $activity->id
,
640 'voter_id' => $activity->voter_id
,
641 'voter_name' => $activity->voter_name
,
642 'status_id' => $activity->status_id
,
643 'interviewer_id' => $activity->interviewer_id
,
644 'result' => $activity->result
,
645 'activity_date_time' => $activity->activity_date_time
653 * This function retrieve survey voter information.
655 * @param int $surveyId survey id.
656 * @param int $interviewerId interviewer id.
657 * @param array $statusIds survey status ids.
659 * @return array $$contactIds survey related contact ids.
662 static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array( )) {
668 $cacheKey = $surveyId;
669 if ($interviewerId) {
670 $cacheKey .= "_{$interviewerId}";
672 if (is_array($statusIds) && !empty($statusIds)) {
673 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
676 static $contactIds = array();
677 if (!isset($contactIds[$cacheKey])) {
678 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
679 foreach ($activities as $values) {
680 $voterIds[$values['voter_id']] = $values;
682 $contactIds[$cacheKey] = $voterIds;
685 return $contactIds[$cacheKey];
689 * This function retrieve all option groups which are created as a result set
691 * @return $resultSets an array of option groups.
694 static function getResultSets( $valueColumnName = 'title' ) {
695 $resultSets = array();
696 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
698 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
699 $dao = CRM_Core_DAO
::executeQuery($query);
700 while ($dao->fetch()) {
701 $resultSets[$dao->id
] = $dao->$valueColumnName;
708 * This function is to check survey activity.
710 * @param int $activityId activity id.
711 * @param int $activityTypeId activity type id.
712 * @return boolean $isSurveyActivity true/false boolean.
715 static function isSurveyActivity($activityId) {
716 $isSurveyActivity = FALSE;
718 return $isSurveyActivity;
721 $activity = new CRM_Activity_DAO_Activity();
722 $activity->id
= $activityId;
723 $activity->selectAdd('source_record_id, activity_type_id');
724 if ($activity->find(TRUE) &&
725 $activity->source_record_id
727 $surveyActTypes = self
::getSurveyActivityType();
728 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
729 $isSurveyActivity = TRUE;
733 return $isSurveyActivity;
737 * This function retrive all response options of survey
739 * @param int $surveyId survey id.
740 * @return $responseOptions an array of option values
743 static function getResponsesOptions($surveyId) {
744 $responseOptions = array();
746 return $responseOptions;
749 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
751 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
754 return $responseOptions;
758 * This function return all voter links with respecting permissions
760 * @return $url array of permissioned links
763 static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
764 $menuLinks = array();
769 static $voterLinks = array();
770 if (empty($voterLinks)) {
771 $permissioned = FALSE;
772 if (CRM_Core_Permission
::check('manage campaign') ||
773 CRM_Core_Permission
::check('administer CiviCampaign')
775 $permissioned = TRUE;
778 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
779 $voterLinks['reserve'] = array(
781 'url' => 'civicrm/survey/search',
782 'qs' => 'sid=%%id%%&reset=1&op=reserve&force=1',
783 'title' => ts('Reserve Respondents'),
786 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
787 $voterLinks['release'] = array(
788 'name' => 'interview',
789 'url' => 'civicrm/survey/search',
790 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
791 'title' => ts('Interview Respondents'),
794 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
795 $voterLinks['interview'] = array(
797 'url' => 'civicrm/survey/search',
798 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
799 'title' => ts('Release Respondents'),
804 if (CRM_Core_Permission
::check('access CiviReport')) {
805 $reportID = self
::getReportID($surveyId);
807 $voterLinks['report'] =
810 'url' => "civicrm/report/instance/{$reportID}",
812 'title' => ts('View Survey Report'),
817 $ids = array('id' => $surveyId);
818 foreach ($voterLinks as $link) {
819 if (CRM_Utils_Array
::value('qs', $link) &&
820 !CRM_Utils_System
::isNull($link['qs'])
822 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
823 CRM_Core_Action
::replace($link['qs'], $ids)
825 $menuLinks[] = sprintf('<a href="%s" class="action-item" title="%s">%s</a>',
827 CRM_Utils_Array
::value('title', $link),
833 $extraLinksName = strtolower($extraULName);
835 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
836 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
837 $menuLinks = "<span class='btn-slide' id={$extraLinksName}_xx>{$allLinks}</span>";
844 * Function to retrieve survey associated profile id.
847 public static function getSurveyProfileId($surveyId) {
852 static $ufIds = array();
853 if (!array_key_exists($surveyId, $ufIds)) {
854 //get the profile id.
855 $ufJoinParams = array(
856 'entity_id' => $surveyId,
857 'entity_table' => 'civicrm_survey',
858 'module' => 'CiviCampaign',
861 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
864 $ufIds[$surveyId] = array($first);
867 $ufIds[$surveyId][] = array_shift($second);
871 return $ufIds[$surveyId];
874 public Static function getReportID($surveyId) {
875 static $reportIds = array();
877 if (!array_key_exists($surveyId, $reportIds)) {
878 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
879 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}",'String')));
880 $reportIds[$surveyId] = $reportID;
882 return $reportIds[$surveyId];
886 * Function to decides the contact type for given survey.
889 public static function getSurveyContactType($surveyId) {
892 //apply filter of profile type on search.
893 $profileId = self
::getSurveyProfileId($surveyId);
895 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
896 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
897 $contactType = $profileType;
905 * Function to get survey supportable profile types
908 public static function surveyProfileTypes() {
909 static $profileTypes;
911 if (!isset($profileTypes)) {
912 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
913 $profileTypes = array_diff($profileTypes, array('Organization','Household'));
916 return $profileTypes;
920 * Get the valid survey response fields those
921 * are configured with profile and custom fields.
923 * @param int $surveyId survey id.
924 * @param int $surveyTypeId survey activity type id.
926 * @return array an array of valid survey response fields.
928 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
929 if (empty($surveyId)) {
933 static $responseFields;
934 $cacheKey = "{$surveyId}_{$surveyTypeId}";
936 if (isset($responseFields[$cacheKey])) {
937 return $responseFields[$cacheKey];
940 $responseFields[$cacheKey] = array();
942 $profileId = self
::getSurveyProfileId($surveyId);
945 return $responseFields;
948 if (!$surveyTypeId) {
949 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
952 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
953 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
956 //don't load these fields in grid.
957 $removeFields = array('File', 'RichTextEditor');
959 $supportableFieldTypes = self
::surveyProfileTypes();
961 // get custom fields of type survey
962 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
964 foreach ($profileFields as $name => $field) {
965 //get only contact and activity fields.
966 //later stage we might going to consider contact type also.
967 if (in_array($field['field_type'], $supportableFieldTypes)) {
968 // we should allow all supported custom data for survey
969 // In case of activity, allow normal activity and with subtype survey,
970 // suppress custom data of other activity types
971 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
972 if (!in_array($field['html_type'], $removeFields)) {
973 if ($field['field_type'] != 'Activity') {
974 $responseFields[$cacheKey][$name] = $field;
976 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
977 $responseFields[$cacheKey][$name] = $field;
982 $responseFields[$cacheKey][$name] = $field;
987 return $responseFields[$cacheKey];
991 * Get all interviewers of surveys.
993 * @return array an array of valid survey response fields.
995 public static function getInterviewers() {
996 static $interviewers;
998 if (isset($interviewers)) {
999 return $interviewers;
1002 $whereClause = NULL;
1003 $activityTypes = self
::getSurveyActivityType();
1004 if (!empty($activityTypes)) {
1005 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1008 $interviewers = array();
1009 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1010 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1013 SELECT contact.id as id,
1014 contact.sort_name as sort_name
1015 FROM civicrm_contact contact
1016 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1017 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1018 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1021 $interviewer = CRM_Core_DAO
::executeQuery($query);
1022 while ($interviewer->fetch()) {
1023 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1026 return $interviewers;
1030 * Check and update the survey respondents.
1032 * @return array success message
1034 public function releaseRespondent($params) {
1035 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1036 $reserveStatusId = array_search('Scheduled', $activityStatus);
1037 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1038 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1040 //retrieve all survey activities related to reserve action.
1042 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1044 SELECT activity.id as id,
1045 activity.activity_date_time as activity_date_time,
1046 survey.id as surveyId,
1047 survey.release_frequency as release_frequency
1048 FROM civicrm_activity activity
1049 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1050 WHERE activity.is_deleted = 0
1051 AND activity.status_id = %1
1052 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1053 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1054 $releasedIds = array();
1055 while ($activity->fetch()) {
1056 if (!$activity->release_frequency
) {
1059 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1060 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1061 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1062 if ($totalReservedSeconds < time()) {
1063 $releasedIds[$activity->id
] = $activity->id
;
1067 //released respondent.
1068 if (!empty($releasedIds)) {
1070 UPDATE civicrm_activity
1072 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1073 CRM_Core_DAO
::executeQuery($query);
1074 $releasedCount = count($releasedIds);
1080 'messages' => "Number of respondents released = {$releasedCount}",