3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * Takes a bunch of params that are needed to match certain criteria and
44 * retrieves the relevant objects. Typically the valid params are only
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.
54 * The action links that we need to display for the browse screen
56 * @param array $params
59 * @return CRM_Campaign_DAO_Survey|null
61 public static function retrieve(&$params, &$defaults) {
62 $dao = new CRM_Campaign_DAO_Survey();
64 $dao->copyValues($params);
66 if ($dao->find(TRUE)) {
67 CRM_Core_DAO
::storeValues($dao, $defaults);
74 * Takes an associative array and creates a Survey object
76 * the function extract all the params it needs to initialize the create a
80 * @param array $params
82 * @return CRM_Survey_DAO_Survey
84 public static function create(&$params) {
89 if (!empty($params['is_default'])) {
90 $query = "UPDATE civicrm_survey SET is_default = 0";
91 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
94 if (!(CRM_Utils_Array
::value('id', $params))) {
96 if (!(CRM_Utils_Array
::value('created_id', $params))) {
97 $session = CRM_Core_Session
::singleton();
98 $params['created_id'] = $session->get('userID');
100 if (!(CRM_Utils_Array
::value('created_date', $params))) {
101 $params['created_date'] = date('YmdHis');
105 $dao = new CRM_Campaign_DAO_Survey();
106 $dao->copyValues($params);
109 if (!empty($params['custom']) &&
110 is_array($params['custom'])
112 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
118 * Retrieve surveys for dashboard.
121 public static function getSurveySummary($params = array(), $onlyCount = FALSE) {
122 //build the limit and order clause.
123 $limitClause = $orderByClause = $lookupTableJoins = NULL;
126 'sort' => 'created_date',
129 'sortOrder' => 'desc',
131 foreach ($sortParams as $name => $default) {
132 if (!empty($params[$name])) {
133 $sortParams[$name] = $params[$name];
137 //need to lookup tables.
138 $orderOnSurveyTable = TRUE;
139 if ($sortParams['sort'] == 'campaign') {
140 $orderOnSurveyTable = FALSE;
141 $lookupTableJoins = '
142 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
143 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
145 elseif ($sortParams['sort'] == 'activity_type') {
146 $orderOnSurveyTable = FALSE;
147 $lookupTableJoins = "
148 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
149 OR survey.activity_type_id IS NULL )
150 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
151 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
153 elseif ($sortParams['sort'] == 'isActive') {
154 $sortParams['sort'] = 'is_active';
156 if ($orderOnSurveyTable) {
157 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
159 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
162 //build the where clause.
163 $queryParams = $where = array();
165 //we only have activity type as a
166 //difference between survey and petition.
167 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
168 if ($petitionTypeID) {
169 $where[] = "( survey.activity_type_id != %1 )";
170 $queryParams[1] = array($petitionTypeID, 'Positive');
173 if (!empty($params['title'])) {
174 $where[] = "( survey.title LIKE %2 )";
175 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
177 if (!empty($params['campaign_id'])) {
178 $where[] = '( survey.campaign_id = %3 )';
179 $queryParams[3] = array($params['campaign_id'], 'Positive');
181 if (!empty($params['activity_type_id'])) {
182 $typeId = $params['activity_type_id'];
183 if (is_array($params['activity_type_id'])) {
184 $typeId = implode(' , ', $params['activity_type_id']);
186 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
189 if (!empty($where)) {
190 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
194 SELECT survey.id as id,
195 survey.title as title,
196 survey.is_active as is_active,
197 survey.result_id as result_id,
198 survey.is_default as is_default,
199 survey.campaign_id as campaign_id,
200 survey.activity_type_id as activity_type_id,
201 survey.release_frequency as release_frequency,
202 survey.max_number_of_contacts as max_number_of_contacts,
203 survey.default_number_of_contacts as default_number_of_contacts';
205 $selectClause = 'SELECT COUNT(*)';
207 $fromClause = 'FROM civicrm_survey survey';
209 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
213 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
226 'max_number_of_contacts',
227 'default_number_of_contacts',
230 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
231 while ($survey->fetch()) {
232 foreach ($properties as $property) {
233 $surveys[$survey->id
][$property] = $survey->$property;
241 * Get the survey count.
244 public static function getSurveyCount() {
245 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
251 * @param bool $onlyActive
252 * Retrieve only active surveys.
253 * @param bool $onlyDefault
254 * Retrieve only default survey.
255 * @param bool $forceAll
256 * Retrieve all surveys.
257 * @param bool $includePetition
258 * Include or exclude petitions.
261 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
263 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
264 foreach ($cacheKeyParams as $param) {
265 $cacheParam = $
$param;
269 $cacheKey .= '_' . $cacheParam;
274 if (!isset($surveys[$cacheKey])) {
275 if (!$includePetition) {
276 //we only have activity type as a
277 //difference between survey and petition.
278 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
281 if ($petitionTypeID) {
282 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
285 if (!$forceAll && $onlyActive) {
286 $where[] = '( survey.is_active = 1 )';
288 if (!$forceAll && $onlyDefault) {
289 $where[] = '( survey.is_default = 1 )';
291 $whereClause = implode(' AND ', $where);
294 SELECT survey.id as id,
295 survey.title as title
296 FROM civicrm_survey as survey
297 WHERE {$whereClause}";
298 $surveys[$cacheKey] = array();
299 $survey = CRM_Core_DAO
::executeQuery($query);
300 while ($survey->fetch()) {
301 $surveys[$cacheKey][$survey->id
] = $survey->title
;
305 return $surveys[$cacheKey];
309 * Get Survey activity types.
311 public static function getSurveyActivityType($returnColumn = 'label', $includePetitionActivityType = FALSE) {
312 static $activityTypes;
313 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
315 if (!isset($activityTypes[$cacheKey])) {
316 $activityTypes = array();
317 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
318 if ($campaignCompId) {
319 $condition = " AND v.component_id={$campaignCompId}";
320 if (!$includePetitionActivityType) {
321 $condition .= " AND v.name != 'Petition'";
323 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
330 if (!empty($activityTypes[$cacheKey])) {
331 return $activityTypes[$cacheKey];
339 * Get Surveys custom groups
341 * @param array $surveyTypes
342 * an array of survey type id.
346 public static function getSurveyCustomGroups($surveyTypes = array()) {
347 $customGroups = array();
348 if (!is_array($surveyTypes)) {
349 $surveyTypes = array($surveyTypes);
352 if (!empty($surveyTypes)) {
353 $activityTypes = array_flip($surveyTypes);
356 $activityTypes = self
::getSurveyActivityType();
359 if (!empty($activityTypes)) {
360 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
362 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
363 FROM civicrm_custom_group cg
364 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
366 $dao = CRM_Core_DAO
::executeQuery($query);
367 while ($dao->fetch()) {
368 $customGroups[$dao->id
]['id'] = $dao->id
;
369 $customGroups[$dao->id
]['name'] = $dao->name
;
370 $customGroups[$dao->id
]['title'] = $dao->title
;
371 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
375 return $customGroups;
379 * Update the is_active flag in the db
382 * Id of the database record.
383 * @param bool $is_active
384 * Value we want to set the is_active field.
387 * DAO object on sucess, null otherwise
389 public static function setIsActive($id, $is_active) {
390 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
401 public static function del($id) {
405 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
407 CRM_Report_BAO_ReportInstance
::del($reportId);
409 $dao = new CRM_Campaign_DAO_Survey();
411 return $dao->delete();
415 * This function retrieve contact information.
417 * @param array $voterIds
418 * @param array $returnProperties
419 * An array of return elements.
422 * array of contact info.
424 public static function voterDetails($voterIds, $returnProperties = array()) {
425 $voterDetails = array();
426 if (!is_array($voterIds) ||
empty($voterIds)) {
427 return $voterDetails;
430 if (empty($returnProperties)) {
431 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
432 'contact_autocomplete_options'
434 $returnProperties = array_fill_keys(array_merge(array(
439 array_keys($autocompleteContactSearch)
443 $select = $from = array();
444 foreach ($returnProperties as $property => $ignore) {
445 $value = (in_array($property, array(
448 ))) ?
'address' : $property;
452 case 'contact_sub_type':
453 $select[] = "$property as $property";
454 $from['contact'] = 'civicrm_contact contact';
460 case 'street_address':
461 $select[] = "$property as $property";
462 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
466 case 'state_province':
467 $select[] = "{$property}.name as $property";
468 if (!in_array('address', $from)) {
469 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
471 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
476 //finally retrieve contact details.
477 if (!empty($select) && !empty($from)) {
478 $fromClause = implode(' ', $from);
479 $selectClause = implode(', ', $select);
480 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
483 SELECT contact.id as contactId, $selectClause
486 Group By contact.id";
488 $contact = CRM_Core_DAO
::executeQuery($query);
489 while ($contact->fetch()) {
490 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
491 foreach ($returnProperties as $property => $ignore) {
492 $voterDetails[$contact->contactId
][$property] = $contact->$property;
494 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
498 $voterDetails[$contact->contactId
]['contact_type'] = $image;
503 return $voterDetails;
507 * This function retrieve survey related activities w/ for give voter ids.
509 * @param int $surveyId
511 * @param array $voterIds
514 * @param int $interviewerId
515 * @param array $statusIds
518 * array of survey activity.
520 public static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL, $statusIds = array()) {
521 $activityDetails = array();
523 !is_array($voterIds) ||
empty($voterIds)
525 return $activityDetails;
529 if (is_array($statusIds) && !empty($statusIds)) {
530 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
533 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
534 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
535 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
536 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
538 $params[1] = array($surveyId, 'Integer');
540 SELECT activity.id, activity.status_id,
541 activityTarget.contact_id as voter_id,
542 activityAssignment.contact_id as interviewer_id
543 FROM civicrm_activity activity
544 INNER JOIN civicrm_activity_contact activityTarget
545 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
546 INNER JOIN civicrm_activity_contact activityAssignment
547 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
548 WHERE activity.source_record_id = %1
549 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
550 if (!empty($interviewerId)) {
551 $query .= "AND activityAssignment.contact_id = %2 ";
552 $params[2] = array($interviewerId, 'Integer');
554 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
556 $activity = CRM_Core_DAO
::executeQuery($query, $params);
557 while ($activity->fetch()) {
558 $activityDetails[$activity->voter_id
] = array(
559 'voter_id' => $activity->voter_id
,
560 'status_id' => $activity->status_id
,
561 'activity_id' => $activity->id
,
562 'interviewer_id' => $activity->interviewer_id
,
566 return $activityDetails;
570 * This function retrieve survey related activities.
572 * @param int $surveyId
573 * @param int $interviewerId
574 * @param array $statusIds
575 * @param array $voterIds
576 * @param bool $onlyCount
579 * An array of survey activity.
581 public static function getSurveyActivities(
583 $interviewerId = NULL,
588 $activities = array();
589 $surveyActivityCount = 0;
591 return ($onlyCount) ?
0 : $activities;
595 if (!empty($statusIds)) {
596 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
599 if ($interviewerId) {
600 $where[] = "( activityAssignment.contact_id = $interviewerId )";
603 if (!empty($voterIds)) {
604 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
608 if (!empty($where)) {
609 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
612 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
618 $select = "SELECT count(activity.id)";
622 SELECT activity.id, activity.status_id,
623 activityTarget.contact_id as voter_id,
624 activityAssignment.contact_id as interviewer_id,
625 activity.result as result,
626 activity.activity_date_time as activity_date_time,
627 contact_a.display_name as voter_name";
630 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
631 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
632 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
636 FROM civicrm_activity activity
637 INNER JOIN civicrm_activity_contact activityTarget
638 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
639 INNER JOIN civicrm_activity_contact activityAssignment
640 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
641 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
642 WHERE activity.source_record_id = %1
643 AND activity.activity_type_id = %2
644 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
648 1 => array($surveyId, 'Integer'),
649 2 => array($actTypeId, 'Integer'),
653 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
654 return ($dbCount) ?
$dbCount : 0;
657 $activity = CRM_Core_DAO
::executeQuery($query, $params);
659 while ($activity->fetch()) {
660 $activities[$activity->id
] = array(
661 'id' => $activity->id
,
662 'voter_id' => $activity->voter_id
,
663 'voter_name' => $activity->voter_name
,
664 'status_id' => $activity->status_id
,
665 'interviewer_id' => $activity->interviewer_id
,
666 'result' => $activity->result
,
667 'activity_date_time' => $activity->activity_date_time
,
675 * Retrieve survey voter information.
677 * @param int $surveyId
679 * @param int $interviewerId
681 * @param array $statusIds
685 * Survey related contact ids.
687 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
693 $cacheKey = $surveyId;
694 if ($interviewerId) {
695 $cacheKey .= "_{$interviewerId}";
697 if (is_array($statusIds) && !empty($statusIds)) {
698 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
701 static $contactIds = array();
702 if (!isset($contactIds[$cacheKey])) {
703 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
704 foreach ($activities as $values) {
705 $voterIds[$values['voter_id']] = $values;
707 $contactIds[$cacheKey] = $voterIds;
710 return $contactIds[$cacheKey];
714 * This function retrieve all option groups which are created as a result set
716 * @param string $valueColumnName
718 * an array of option groups.
720 public static function getResultSets($valueColumnName = 'title') {
721 $resultSets = array();
722 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
724 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
725 $dao = CRM_Core_DAO
::executeQuery($query);
726 while ($dao->fetch()) {
727 $resultSets[$dao->id
] = $dao->$valueColumnName;
734 * check survey activity.
736 * @param int $activityId
740 public static function isSurveyActivity($activityId) {
741 $isSurveyActivity = FALSE;
743 return $isSurveyActivity;
746 $activity = new CRM_Activity_DAO_Activity();
747 $activity->id
= $activityId;
748 $activity->selectAdd('source_record_id, activity_type_id');
749 if ($activity->find(TRUE) &&
750 $activity->source_record_id
752 $surveyActTypes = self
::getSurveyActivityType();
753 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
754 $isSurveyActivity = TRUE;
758 return $isSurveyActivity;
762 * This function retrive all response options of survey
764 * @param int $surveyId
767 * an array of option values
769 public static function getResponsesOptions($surveyId) {
770 $responseOptions = array();
772 return $responseOptions;
775 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
777 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
780 return $responseOptions;
784 * This function return all voter links with respecting permissions
786 * @param int $surveyId
787 * @param bool $enclosedInUL
788 * @param string $extraULName
789 * @return array|string
790 * $url array of permissioned links
792 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
793 $menuLinks = array();
798 static $voterLinks = array();
799 if (empty($voterLinks)) {
800 $permissioned = FALSE;
801 if (CRM_Core_Permission
::check('manage campaign') ||
802 CRM_Core_Permission
::check('administer CiviCampaign')
804 $permissioned = TRUE;
807 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
808 $voterLinks['reserve'] = array(
810 'url' => 'civicrm/survey/search',
811 'qs' => 'sid=%%id%%&reset=1&op=reserve',
812 'title' => ts('Reserve Respondents'),
815 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
816 $voterLinks['release'] = array(
817 'name' => 'interview',
818 'url' => 'civicrm/survey/search',
819 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
820 'title' => ts('Interview Respondents'),
823 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
824 $voterLinks['interview'] = array(
826 'url' => 'civicrm/survey/search',
827 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
828 'title' => ts('Release Respondents'),
833 if (CRM_Core_Permission
::check('access CiviReport')) {
834 $reportID = self
::getReportID($surveyId);
836 $voterLinks['report'] = array(
838 'url' => "civicrm/report/instance/{$reportID}",
840 'title' => ts('View Survey Report'),
845 $ids = array('id' => $surveyId);
846 foreach ($voterLinks as $link) {
847 if (!empty($link['qs']) &&
848 !CRM_Utils_System
::isNull($link['qs'])
850 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
851 CRM_Core_Action
::replace($link['qs'], $ids)
853 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
855 CRM_Utils_Array
::value('title', $link),
861 $extraLinksName = strtolower($extraULName);
863 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
864 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
865 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
872 * Retrieve survey associated profile id.
874 public static function getSurveyProfileId($surveyId) {
879 static $ufIds = array();
880 if (!array_key_exists($surveyId, $ufIds)) {
881 //get the profile id.
882 $ufJoinParams = array(
883 'entity_id' => $surveyId,
884 'entity_table' => 'civicrm_survey',
885 'module' => 'CiviCampaign',
888 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
891 $ufIds[$surveyId] = array($first);
894 $ufIds[$surveyId][] = array_shift($second);
898 return CRM_Utils_Array
::value($surveyId, $ufIds);
902 * @param int $surveyId
906 public Static function getReportID($surveyId) {
907 static $reportIds = array();
909 if (!array_key_exists($surveyId, $reportIds)) {
910 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
911 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
912 $reportIds[$surveyId] = $reportID;
914 return $reportIds[$surveyId];
918 * Decides the contact type for given survey.
920 public static function getSurveyContactType($surveyId) {
923 //apply filter of profile type on search.
924 $profileId = self
::getSurveyProfileId($surveyId);
926 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
927 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
928 $contactType = $profileType;
936 * Get survey supportable profile types
938 public static function surveyProfileTypes() {
939 static $profileTypes;
941 if (!isset($profileTypes)) {
942 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
943 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
946 return $profileTypes;
950 * Get the valid survey response fields those
951 * are configured with profile and custom fields.
953 * @param int $surveyId
955 * @param int $surveyTypeId
956 * Survey activity type id.
959 * an array of valid survey response fields.
961 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
962 if (empty($surveyId)) {
966 static $responseFields;
967 $cacheKey = "{$surveyId}_{$surveyTypeId}";
969 if (isset($responseFields[$cacheKey])) {
970 return $responseFields[$cacheKey];
973 $responseFields[$cacheKey] = array();
975 $profileId = self
::getSurveyProfileId($surveyId);
978 return $responseFields;
981 if (!$surveyTypeId) {
982 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
985 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
986 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
989 //don't load these fields in grid.
990 $removeFields = array('File', 'RichTextEditor');
992 $supportableFieldTypes = self
::surveyProfileTypes();
994 // get custom fields of type survey
995 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
997 foreach ($profileFields as $name => $field) {
998 //get only contact and activity fields.
999 //later stage we might going to consider contact type also.
1000 if (in_array($field['field_type'], $supportableFieldTypes)) {
1001 // we should allow all supported custom data for survey
1002 // In case of activity, allow normal activity and with subtype survey,
1003 // suppress custom data of other activity types
1004 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1005 if (!in_array($field['html_type'], $removeFields)) {
1006 if ($field['field_type'] != 'Activity') {
1007 $responseFields[$cacheKey][$name] = $field;
1009 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1010 $responseFields[$cacheKey][$name] = $field;
1015 $responseFields[$cacheKey][$name] = $field;
1020 return $responseFields[$cacheKey];
1024 * Get all interviewers of surveys.
1027 * an array of valid survey response fields.
1029 public static function getInterviewers() {
1030 static $interviewers;
1032 if (isset($interviewers)) {
1033 return $interviewers;
1036 $whereClause = NULL;
1037 $activityTypes = self
::getSurveyActivityType();
1038 if (!empty($activityTypes)) {
1039 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1042 $interviewers = array();
1043 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1044 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1047 SELECT contact.id as id,
1048 contact.sort_name as sort_name
1049 FROM civicrm_contact contact
1050 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1051 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1052 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1055 $interviewer = CRM_Core_DAO
::executeQuery($query);
1056 while ($interviewer->fetch()) {
1057 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1060 return $interviewers;
1064 * Check and update the survey respondents.
1066 * @param array $params
1071 public static function releaseRespondent($params) {
1072 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1073 $reserveStatusId = array_search('Scheduled', $activityStatus);
1074 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1075 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1076 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1079 //retrieve all survey activities related to reserve action.
1081 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1083 SELECT activity.id as id,
1084 activity.activity_date_time as activity_date_time,
1085 survey.id as surveyId,
1086 survey.release_frequency as release_frequency
1087 FROM civicrm_activity activity
1088 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1089 WHERE activity.is_deleted = 0
1090 AND activity.status_id = %1
1091 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1092 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1093 $releasedIds = array();
1094 while ($activity->fetch()) {
1095 if (!$activity->release_frequency
) {
1098 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1099 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1100 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1101 if ($totalReservedSeconds < time()) {
1102 $releasedIds[$activity->id
] = $activity->id
;
1106 //released respondent.
1107 if (!empty($releasedIds)) {
1109 UPDATE civicrm_activity
1111 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1112 CRM_Core_DAO
::executeQuery($query);
1113 $releasedCount = count($releasedIds);
1119 'messages' => "Number of respondents released = {$releasedCount}",
1126 * Get options for a given field.
1127 * @see CRM_Core_DAO::buildOptions
1129 * @param string $fieldName
1130 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1131 * @param array $props : whatever is known about this dao object
1133 * @return array|bool
1135 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1137 // Special logic for fields whose options depend on context or properties
1138 switch ($fieldName) {
1139 case 'activity_type_id':
1140 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1141 if ($campaignCompId) {
1142 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1146 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);