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 (!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 * 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 (!empty($params[$name])) {
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 (!empty($params['title'])) {
169 $where[] = "( survey.title LIKE %2 )";
170 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
172 if (!empty($params['campaign_id'])) {
173 $where[] = '( survey.campaign_id = %3 )';
174 $queryParams[3] = array($params['campaign_id'], 'Positive');
176 if (!empty($params['activity_type_id'])) {
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 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
514 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
515 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
516 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
518 $params[1] = array($surveyId, 'Integer');
520 SELECT activity.id, activity.status_id,
521 activityTarget.contact_id as voter_id,
522 activityAssignment.contact_id as interviewer_id
523 FROM civicrm_activity activity
524 INNER JOIN civicrm_activity_contact activityTarget
525 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
526 INNER JOIN civicrm_activity_contact activityAssignment
527 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
528 WHERE activity.source_record_id = %1
529 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
530 if(!empty($interviewerId)) {
531 $query .= "AND activityAssignment.contact_id = %2 ";
532 $params[2] = array($interviewerId, 'Integer');
534 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
536 $activity = CRM_Core_DAO
::executeQuery($query, $params);
537 while ($activity->fetch()) {
538 $activityDetails[$activity->voter_id
] = array(
539 'voter_id' => $activity->voter_id
,
540 'status_id' => $activity->status_id
,
541 'activity_id' => $activity->id
,
542 'interviewer_id' => $activity->interviewer_id
,
546 return $activityDetails;
550 * This function retrieve survey related activities.
552 * @param int $surveyId survey id.
554 * @return $activities an array of survey activity.
557 static function getSurveyActivities($surveyId,
558 $interviewerId = NULL,
563 $activities = array();
564 $surveyActivityCount = 0;
566 return ($onlyCount) ?
0 : $activities;
570 if (!empty($statusIds)) {
571 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
574 if ($interviewerId) {
575 $where[] = "( activityAssignment.contact_id = $interviewerId )";
578 if (!empty($voterIds)) {
579 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
583 if (!empty($where)) {
584 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
587 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
593 $select = "SELECT count(activity.id)";
597 SELECT activity.id, activity.status_id,
598 activityTarget.contact_id as voter_id,
599 activityAssignment.contact_id as interviewer_id,
600 activity.result as result,
601 activity.activity_date_time as activity_date_time,
602 contact_a.display_name as voter_name";
605 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
606 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
607 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
611 FROM civicrm_activity activity
612 INNER JOIN civicrm_activity_contact activityTarget
613 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
614 INNER JOIN civicrm_activity_contact activityAssignment
615 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
616 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
617 WHERE activity.source_record_id = %1
618 AND activity.activity_type_id = %2
619 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
622 $params = array(1 => array($surveyId, 'Integer'),
623 2 => array($actTypeId, 'Integer'),
627 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
628 return ($dbCount) ?
$dbCount : 0;
631 $activity = CRM_Core_DAO
::executeQuery($query, $params);
633 while ($activity->fetch()) {
634 $activities[$activity->id
] = array(
635 'id' => $activity->id
,
636 'voter_id' => $activity->voter_id
,
637 'voter_name' => $activity->voter_name
,
638 'status_id' => $activity->status_id
,
639 'interviewer_id' => $activity->interviewer_id
,
640 'result' => $activity->result
,
641 'activity_date_time' => $activity->activity_date_time
649 * This function retrieve survey voter information.
651 * @param int $surveyId survey id.
652 * @param int $interviewerId interviewer id.
653 * @param array $statusIds survey status ids.
655 * @return array $$contactIds survey related contact ids.
658 static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array( )) {
664 $cacheKey = $surveyId;
665 if ($interviewerId) {
666 $cacheKey .= "_{$interviewerId}";
668 if (is_array($statusIds) && !empty($statusIds)) {
669 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
672 static $contactIds = array();
673 if (!isset($contactIds[$cacheKey])) {
674 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
675 foreach ($activities as $values) {
676 $voterIds[$values['voter_id']] = $values;
678 $contactIds[$cacheKey] = $voterIds;
681 return $contactIds[$cacheKey];
685 * This function retrieve all option groups which are created as a result set
687 * @return $resultSets an array of option groups.
690 static function getResultSets( $valueColumnName = 'title' ) {
691 $resultSets = array();
692 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
694 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
695 $dao = CRM_Core_DAO
::executeQuery($query);
696 while ($dao->fetch()) {
697 $resultSets[$dao->id
] = $dao->$valueColumnName;
704 * This function is to check survey activity.
706 * @param int $activityId activity id.
707 * @param int $activityTypeId activity type id.
708 * @return boolean $isSurveyActivity true/false boolean.
711 static function isSurveyActivity($activityId) {
712 $isSurveyActivity = FALSE;
714 return $isSurveyActivity;
717 $activity = new CRM_Activity_DAO_Activity();
718 $activity->id
= $activityId;
719 $activity->selectAdd('source_record_id, activity_type_id');
720 if ($activity->find(TRUE) &&
721 $activity->source_record_id
723 $surveyActTypes = self
::getSurveyActivityType();
724 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
725 $isSurveyActivity = TRUE;
729 return $isSurveyActivity;
733 * This function retrive all response options of survey
735 * @param int $surveyId survey id.
736 * @return $responseOptions an array of option values
739 static function getResponsesOptions($surveyId) {
740 $responseOptions = array();
742 return $responseOptions;
745 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
747 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
750 return $responseOptions;
754 * This function return all voter links with respecting permissions
756 * @return $url array of permissioned links
759 static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
760 $menuLinks = array();
765 static $voterLinks = array();
766 if (empty($voterLinks)) {
767 $permissioned = FALSE;
768 if (CRM_Core_Permission
::check('manage campaign') ||
769 CRM_Core_Permission
::check('administer CiviCampaign')
771 $permissioned = TRUE;
774 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
775 $voterLinks['reserve'] = array(
777 'url' => 'civicrm/survey/search',
778 'qs' => 'sid=%%id%%&reset=1&op=reserve&force=1',
779 'title' => ts('Reserve Respondents'),
782 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
783 $voterLinks['release'] = array(
784 'name' => 'interview',
785 'url' => 'civicrm/survey/search',
786 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
787 'title' => ts('Interview Respondents'),
790 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
791 $voterLinks['interview'] = array(
793 'url' => 'civicrm/survey/search',
794 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
795 'title' => ts('Release Respondents'),
800 if (CRM_Core_Permission
::check('access CiviReport')) {
801 $reportID = self
::getReportID($surveyId);
803 $voterLinks['report'] =
806 'url' => "civicrm/report/instance/{$reportID}",
808 'title' => ts('View Survey Report'),
813 $ids = array('id' => $surveyId);
814 foreach ($voterLinks as $link) {
815 if (!empty($link['qs']) &&
816 !CRM_Utils_System
::isNull($link['qs'])
818 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
819 CRM_Core_Action
::replace($link['qs'], $ids)
821 $menuLinks[] = sprintf('<a href="%s" class="action-item" title="%s">%s</a>',
823 CRM_Utils_Array
::value('title', $link),
829 $extraLinksName = strtolower($extraULName);
831 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
832 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
833 $menuLinks = "<span class='btn-slide' id={$extraLinksName}_xx>{$allLinks}</span>";
840 * Function to retrieve survey associated profile id.
843 public static function getSurveyProfileId($surveyId) {
848 static $ufIds = array();
849 if (!array_key_exists($surveyId, $ufIds)) {
850 //get the profile id.
851 $ufJoinParams = array(
852 'entity_id' => $surveyId,
853 'entity_table' => 'civicrm_survey',
854 'module' => 'CiviCampaign',
857 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
860 $ufIds[$surveyId] = array($first);
863 $ufIds[$surveyId][] = array_shift($second);
867 return CRM_Utils_Array
::value($surveyId, $ufIds);
870 public Static function getReportID($surveyId) {
871 static $reportIds = array();
873 if (!array_key_exists($surveyId, $reportIds)) {
874 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
875 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}",'String')));
876 $reportIds[$surveyId] = $reportID;
878 return $reportIds[$surveyId];
882 * Function to decides the contact type for given survey.
885 public static function getSurveyContactType($surveyId) {
888 //apply filter of profile type on search.
889 $profileId = self
::getSurveyProfileId($surveyId);
891 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
892 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
893 $contactType = $profileType;
901 * Function to get survey supportable profile types
904 public static function surveyProfileTypes() {
905 static $profileTypes;
907 if (!isset($profileTypes)) {
908 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
909 $profileTypes = array_diff($profileTypes, array('Organization','Household'));
912 return $profileTypes;
916 * Get the valid survey response fields those
917 * are configured with profile and custom fields.
919 * @param int $surveyId survey id.
920 * @param int $surveyTypeId survey activity type id.
922 * @return array an array of valid survey response fields.
924 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
925 if (empty($surveyId)) {
929 static $responseFields;
930 $cacheKey = "{$surveyId}_{$surveyTypeId}";
932 if (isset($responseFields[$cacheKey])) {
933 return $responseFields[$cacheKey];
936 $responseFields[$cacheKey] = array();
938 $profileId = self
::getSurveyProfileId($surveyId);
941 return $responseFields;
944 if (!$surveyTypeId) {
945 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
948 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
949 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
952 //don't load these fields in grid.
953 $removeFields = array('File', 'RichTextEditor');
955 $supportableFieldTypes = self
::surveyProfileTypes();
957 // get custom fields of type survey
958 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
960 foreach ($profileFields as $name => $field) {
961 //get only contact and activity fields.
962 //later stage we might going to consider contact type also.
963 if (in_array($field['field_type'], $supportableFieldTypes)) {
964 // we should allow all supported custom data for survey
965 // In case of activity, allow normal activity and with subtype survey,
966 // suppress custom data of other activity types
967 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
968 if (!in_array($field['html_type'], $removeFields)) {
969 if ($field['field_type'] != 'Activity') {
970 $responseFields[$cacheKey][$name] = $field;
972 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
973 $responseFields[$cacheKey][$name] = $field;
978 $responseFields[$cacheKey][$name] = $field;
983 return $responseFields[$cacheKey];
987 * Get all interviewers of surveys.
989 * @return array an array of valid survey response fields.
991 public static function getInterviewers() {
992 static $interviewers;
994 if (isset($interviewers)) {
995 return $interviewers;
999 $activityTypes = self
::getSurveyActivityType();
1000 if (!empty($activityTypes)) {
1001 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1004 $interviewers = array();
1005 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1006 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1009 SELECT contact.id as id,
1010 contact.sort_name as sort_name
1011 FROM civicrm_contact contact
1012 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1013 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1014 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1017 $interviewer = CRM_Core_DAO
::executeQuery($query);
1018 while ($interviewer->fetch()) {
1019 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1022 return $interviewers;
1026 * Check and update the survey respondents.
1028 * @return array success message
1030 public function releaseRespondent($params) {
1031 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1032 $reserveStatusId = array_search('Scheduled', $activityStatus);
1033 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1034 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1036 //retrieve all survey activities related to reserve action.
1038 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1040 SELECT activity.id as id,
1041 activity.activity_date_time as activity_date_time,
1042 survey.id as surveyId,
1043 survey.release_frequency as release_frequency
1044 FROM civicrm_activity activity
1045 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1046 WHERE activity.is_deleted = 0
1047 AND activity.status_id = %1
1048 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1049 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1050 $releasedIds = array();
1051 while ($activity->fetch()) {
1052 if (!$activity->release_frequency
) {
1055 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1056 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1057 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1058 if ($totalReservedSeconds < time()) {
1059 $releasedIds[$activity->id
] = $activity->id
;
1063 //released respondent.
1064 if (!empty($releasedIds)) {
1066 UPDATE civicrm_activity
1068 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1069 CRM_Core_DAO
::executeQuery($query);
1070 $releasedCount = count($releasedIds);
1076 'messages' => "Number of respondents released = {$releasedCount}",
1083 * Get options for a given field.
1084 * @see CRM_Core_DAO::buildOptions
1086 * @param String $fieldName
1087 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
1088 * @param Array $props: whatever is known about this dao object
1090 * @return array|bool
1092 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1094 // Special logic for fields whose options depend on context or properties
1095 switch ($fieldName) {
1096 case 'activity_type_id':
1097 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1098 if ($campaignCompId) {
1099 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1103 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);