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.
55 * The action links that we need to display for the browse screen
57 * @param array $params
60 * @return CRM_Campaign_DAO_Survey|null
62 public static function retrieve(&$params, &$defaults) {
63 $dao = new CRM_Campaign_DAO_Survey();
65 $dao->copyValues($params);
67 if ($dao->find(TRUE)) {
68 CRM_Core_DAO
::storeValues($dao, $defaults);
75 * Takes an associative array and creates a Survey object
77 * the function extract all the params it needs to initialize the create a
81 * @param array $params
83 * @return CRM_Survey_DAO_Survey object
86 public static function create(&$params) {
91 if (!empty($params['is_default'])) {
92 $query = "UPDATE civicrm_survey SET is_default = 0";
93 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
96 if (!(CRM_Utils_Array
::value('id', $params))) {
98 if (!(CRM_Utils_Array
::value('created_id', $params))) {
99 $session = CRM_Core_Session
::singleton();
100 $params['created_id'] = $session->get('userID');
102 if (!(CRM_Utils_Array
::value('created_date', $params))) {
103 $params['created_date'] = date('YmdHis');
107 $dao = new CRM_Campaign_DAO_Survey();
108 $dao->copyValues($params);
111 if (!empty($params['custom']) &&
112 is_array($params['custom'])
114 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
120 * Retrieve surveys for dashboard.
124 public static function getSurveySummary($params = array(), $onlyCount = FALSE) {
125 //build the limit and order clause.
126 $limitClause = $orderByClause = $lookupTableJoins = NULL;
129 'sort' => 'created_date',
132 'sortOrder' => 'desc',
134 foreach ($sortParams as $name => $default) {
135 if (!empty($params[$name])) {
136 $sortParams[$name] = $params[$name];
140 //need to lookup tables.
141 $orderOnSurveyTable = TRUE;
142 if ($sortParams['sort'] == 'campaign') {
143 $orderOnSurveyTable = FALSE;
144 $lookupTableJoins = '
145 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
146 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
148 elseif ($sortParams['sort'] == 'activity_type') {
149 $orderOnSurveyTable = FALSE;
150 $lookupTableJoins = "
151 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
152 OR survey.activity_type_id IS NULL )
153 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
154 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
156 elseif ($sortParams['sort'] == 'isActive') {
157 $sortParams['sort'] = 'is_active';
159 if ($orderOnSurveyTable) {
160 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
162 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
165 //build the where clause.
166 $queryParams = $where = array();
168 //we only have activity type as a
169 //difference between survey and petition.
170 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
171 if ($petitionTypeID) {
172 $where[] = "( survey.activity_type_id != %1 )";
173 $queryParams[1] = array($petitionTypeID, 'Positive');
176 if (!empty($params['title'])) {
177 $where[] = "( survey.title LIKE %2 )";
178 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
180 if (!empty($params['campaign_id'])) {
181 $where[] = '( survey.campaign_id = %3 )';
182 $queryParams[3] = array($params['campaign_id'], 'Positive');
184 if (!empty($params['activity_type_id'])) {
185 $typeId = $params['activity_type_id'];
186 if (is_array($params['activity_type_id'])) {
187 $typeId = implode(' , ', $params['activity_type_id']);
189 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
192 if (!empty($where)) {
193 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
197 SELECT survey.id as id,
198 survey.title as title,
199 survey.is_active as is_active,
200 survey.result_id as result_id,
201 survey.is_default as is_default,
202 survey.campaign_id as campaign_id,
203 survey.activity_type_id as activity_type_id,
204 survey.release_frequency as release_frequency,
205 survey.max_number_of_contacts as max_number_of_contacts,
206 survey.default_number_of_contacts as default_number_of_contacts';
208 $selectClause = 'SELECT COUNT(*)';
210 $fromClause = 'FROM civicrm_survey survey';
212 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
216 return (int) CRM_Core_DAO
::singleValueQuery($query, $queryParams);
221 'id', 'title', 'campaign_id', 'is_active', 'is_default', 'result_id', 'activity_type_id',
222 'release_frequency', 'max_number_of_contacts', 'default_number_of_contacts',
225 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
226 while ($survey->fetch()) {
227 foreach ($properties as $property) {
228 $surveys[$survey->id
][$property] = $survey->$property;
236 * Get the survey count.
240 public static function getSurveyCount() {
241 return (int) CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
247 * @param bool $onlyActive
248 * Retrieve only active surveys.
249 * @param bool $onlyDefault
250 * Retrieve only default survey.
251 * @param bool $forceAll
252 * Retrieve all surveys.
253 * @param bool $includePetition
254 * Include or exclude petitions.
258 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
260 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
261 foreach ($cacheKeyParams as $param) {
262 $cacheParam = $
$param;
266 $cacheKey .= '_' . $cacheParam;
271 if (!isset($surveys[$cacheKey])) {
272 if (!$includePetition) {
273 //we only have activity type as a
274 //difference between survey and petition.
275 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
278 if ($petitionTypeID) {
279 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
282 if (!$forceAll && $onlyActive) {
283 $where[] = '( survey.is_active = 1 )';
285 if (!$forceAll && $onlyDefault) {
286 $where[] = '( survey.is_default = 1 )';
288 $whereClause = implode(' AND ', $where);
291 SELECT survey.id as id,
292 survey.title as title
293 FROM civicrm_survey as survey
294 WHERE {$whereClause}";
295 $surveys[$cacheKey] = array();
296 $survey = CRM_Core_DAO
::executeQuery($query);
297 while ($survey->fetch()) {
298 $surveys[$cacheKey][$survey->id
] = $survey->title
;
302 return $surveys[$cacheKey];
306 * Get Surveys activity types
311 static function getSurveyActivityType(
312 $returnColumn = 'label',
313 $includePetitionActivityType = FALSE
315 static $activityTypes;
316 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
318 if (!isset($activityTypes[$cacheKey])) {
319 $activityTypes = array();
320 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
321 if ($campaignCompId) {
322 $condition = " AND v.component_id={$campaignCompId}";
323 if (!$includePetitionActivityType) {
324 $condition .= " AND v.name != 'Petition'";
326 $activityTypes[$cacheKey] = CRM_Core_OptionGroup
::values('activity_type',
333 if (!empty($activityTypes[$cacheKey])) {
334 return $activityTypes[$cacheKey];
342 * Get Surveys custom groups
344 * @param array $surveyTypes
345 * an array of survey type id.
350 public static function getSurveyCustomGroups($surveyTypes = array()) {
351 $customGroups = array();
352 if (!is_array($surveyTypes)) {
353 $surveyTypes = array($surveyTypes);
356 if (!empty($surveyTypes)) {
357 $activityTypes = array_flip($surveyTypes);
360 $activityTypes = self
::getSurveyActivityType();
363 if (!empty($activityTypes)) {
364 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
366 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
367 FROM civicrm_custom_group cg
368 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
370 $dao = CRM_Core_DAO
::executeQuery($query);
371 while ($dao->fetch()) {
372 $customGroups[$dao->id
]['id'] = $dao->id
;
373 $customGroups[$dao->id
]['name'] = $dao->name
;
374 $customGroups[$dao->id
]['title'] = $dao->title
;
375 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
379 return $customGroups;
383 * Update the is_active flag in the db
386 * Id of the database record.
387 * @param bool $is_active
388 * Value we want to set the is_active field.
390 * @return Object DAO object on sucess, null otherwise
393 public static function setIsActive($id, $is_active) {
394 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
407 public static function del($id) {
411 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
413 CRM_Report_BAO_ReportInstance
::del($reportId);
415 $dao = new CRM_Campaign_DAO_Survey();
417 return $dao->delete();
421 * This function retrieve contact information.
423 * @param array $voterIds
424 * @param array $returnProperties
425 * An array of return elements.
427 * @return array $voterDetails array of contact info.
430 public static function voterDetails($voterIds, $returnProperties = array()) {
431 $voterDetails = array();
432 if (!is_array($voterIds) ||
empty($voterIds)) {
433 return $voterDetails;
436 if (empty($returnProperties)) {
437 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
438 'contact_autocomplete_options'
440 $returnProperties = array_fill_keys(array_merge(array(
445 array_keys($autocompleteContactSearch)
449 $select = $from = array();
450 foreach ($returnProperties as $property => $ignore) {
451 $value = (in_array($property, array(
452 'city', 'street_address'))) ?
'address' : $property;
456 case 'contact_sub_type':
457 $select[] = "$property as $property";
458 $from['contact'] = 'civicrm_contact contact';
464 case 'street_address':
465 $select[] = "$property as $property";
466 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
470 case 'state_province':
471 $select[] = "{$property}.name as $property";
472 if (!in_array('address', $from)) {
473 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
475 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
480 //finally retrieve contact details.
481 if (!empty($select) && !empty($from)) {
482 $fromClause = implode(' ', $from);
483 $selectClause = implode(', ', $select);
484 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
487 SELECT contact.id as contactId, $selectClause
490 Group By contact.id";
492 $contact = CRM_Core_DAO
::executeQuery($query);
493 while ($contact->fetch()) {
494 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
495 foreach ($returnProperties as $property => $ignore) {
496 $voterDetails[$contact->contactId
][$property] = $contact->$property;
498 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
$contact->contact_sub_type
: $contact->contact_type
,
502 $voterDetails[$contact->contactId
]['contact_type'] = $image;
507 return $voterDetails;
511 * This function retrieve survey related activities w/ for give voter ids.
513 * @param int $surveyId
515 * @param array $voterIds
518 * @param int $interviewerId
519 * @param array $statusIds
521 * @return array $activityDetails array of survey activity.
524 static function voterActivityDetails(
525 $surveyId, $voterIds, $interviewerId = NULL,
526 $statusIds = array()) {
527 $activityDetails = array();
529 !is_array($voterIds) ||
empty($voterIds)
531 return $activityDetails;
535 if (is_array($statusIds) && !empty($statusIds)) {
536 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
539 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
540 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
541 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
542 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
544 $params[1] = array($surveyId, 'Integer');
546 SELECT activity.id, activity.status_id,
547 activityTarget.contact_id as voter_id,
548 activityAssignment.contact_id as interviewer_id
549 FROM civicrm_activity activity
550 INNER JOIN civicrm_activity_contact activityTarget
551 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
552 INNER JOIN civicrm_activity_contact activityAssignment
553 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
554 WHERE activity.source_record_id = %1
555 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
556 if (!empty($interviewerId)) {
557 $query .= "AND activityAssignment.contact_id = %2 ";
558 $params[2] = array($interviewerId, 'Integer');
560 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
562 $activity = CRM_Core_DAO
::executeQuery($query, $params);
563 while ($activity->fetch()) {
564 $activityDetails[$activity->voter_id
] = array(
565 'voter_id' => $activity->voter_id
,
566 'status_id' => $activity->status_id
,
567 'activity_id' => $activity->id
,
568 'interviewer_id' => $activity->interviewer_id
,
572 return $activityDetails;
576 * This function retrieve survey related activities.
578 * @param int $surveyId
579 * @param int $interviewerId
580 * @param array $statusIds
581 * @param array $voterIds
582 * @param bool $onlyCount
585 * An array of survey activity.
588 static function getSurveyActivities(
590 $interviewerId = NULL,
595 $activities = array();
596 $surveyActivityCount = 0;
598 return ($onlyCount) ?
0 : $activities;
602 if (!empty($statusIds)) {
603 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
606 if ($interviewerId) {
607 $where[] = "( activityAssignment.contact_id = $interviewerId )";
610 if (!empty($voterIds)) {
611 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
615 if (!empty($where)) {
616 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
619 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
625 $select = "SELECT count(activity.id)";
629 SELECT activity.id, activity.status_id,
630 activityTarget.contact_id as voter_id,
631 activityAssignment.contact_id as interviewer_id,
632 activity.result as result,
633 activity.activity_date_time as activity_date_time,
634 contact_a.display_name as voter_name";
637 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
638 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
639 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
643 FROM civicrm_activity activity
644 INNER JOIN civicrm_activity_contact activityTarget
645 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
646 INNER JOIN civicrm_activity_contact activityAssignment
647 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
648 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
649 WHERE activity.source_record_id = %1
650 AND activity.activity_type_id = %2
651 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
655 1 => array($surveyId, 'Integer'),
656 2 => array($actTypeId, 'Integer'),
660 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
661 return ($dbCount) ?
$dbCount : 0;
664 $activity = CRM_Core_DAO
::executeQuery($query, $params);
666 while ($activity->fetch()) {
667 $activities[$activity->id
] = array(
668 'id' => $activity->id
,
669 'voter_id' => $activity->voter_id
,
670 'voter_name' => $activity->voter_name
,
671 'status_id' => $activity->status_id
,
672 'interviewer_id' => $activity->interviewer_id
,
673 'result' => $activity->result
,
674 'activity_date_time' => $activity->activity_date_time
,
682 * Retrieve survey voter information.
684 * @param int $surveyId
686 * @param int $interviewerId
688 * @param array $statusIds
692 * Survey related contact ids.
695 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
701 $cacheKey = $surveyId;
702 if ($interviewerId) {
703 $cacheKey .= "_{$interviewerId}";
705 if (is_array($statusIds) && !empty($statusIds)) {
706 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
709 static $contactIds = array();
710 if (!isset($contactIds[$cacheKey])) {
711 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
712 foreach ($activities as $values) {
713 $voterIds[$values['voter_id']] = $values;
715 $contactIds[$cacheKey] = $voterIds;
718 return $contactIds[$cacheKey];
722 * This function retrieve all option groups which are created as a result set
724 * @param string $valueColumnName
725 * @return array $resultSets an array of option groups.
728 public static function getResultSets($valueColumnName = 'title') {
729 $resultSets = array();
730 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
732 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
733 $dao = CRM_Core_DAO
::executeQuery($query);
734 while ($dao->fetch()) {
735 $resultSets[$dao->id
] = $dao->$valueColumnName;
742 * check survey activity.
744 * @param int $activityId
746 * @return boolean $isSurveyActivity true/false
749 public static function isSurveyActivity($activityId) {
750 $isSurveyActivity = FALSE;
752 return $isSurveyActivity;
755 $activity = new CRM_Activity_DAO_Activity();
756 $activity->id
= $activityId;
757 $activity->selectAdd('source_record_id, activity_type_id');
758 if ($activity->find(TRUE) &&
759 $activity->source_record_id
761 $surveyActTypes = self
::getSurveyActivityType();
762 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
763 $isSurveyActivity = TRUE;
767 return $isSurveyActivity;
771 * This function retrive all response options of survey
773 * @param int $surveyId
775 * @return array $responseOptions an array of option values
778 public static function getResponsesOptions($surveyId) {
779 $responseOptions = array();
781 return $responseOptions;
784 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
786 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
789 return $responseOptions;
793 * This function return all voter links with respecting permissions
795 * @param int $surveyId
796 * @param bool $enclosedInUL
797 * @param string $extraULName
798 * @return array|string $url array of permissioned links
801 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
802 $menuLinks = array();
807 static $voterLinks = array();
808 if (empty($voterLinks)) {
809 $permissioned = FALSE;
810 if (CRM_Core_Permission
::check('manage campaign') ||
811 CRM_Core_Permission
::check('administer CiviCampaign')
813 $permissioned = TRUE;
816 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
817 $voterLinks['reserve'] = array(
819 'url' => 'civicrm/survey/search',
820 'qs' => 'sid=%%id%%&reset=1&op=reserve',
821 'title' => ts('Reserve Respondents'),
824 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
825 $voterLinks['release'] = array(
826 'name' => 'interview',
827 'url' => 'civicrm/survey/search',
828 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
829 'title' => ts('Interview Respondents'),
832 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
833 $voterLinks['interview'] = array(
835 'url' => 'civicrm/survey/search',
836 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
837 'title' => ts('Release Respondents'),
842 if (CRM_Core_Permission
::check('access CiviReport')) {
843 $reportID = self
::getReportID($surveyId);
845 $voterLinks['report'] =
848 'url' => "civicrm/report/instance/{$reportID}",
850 'title' => ts('View Survey Report'),
855 $ids = array('id' => $surveyId);
856 foreach ($voterLinks as $link) {
857 if (!empty($link['qs']) &&
858 !CRM_Utils_System
::isNull($link['qs'])
860 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
861 CRM_Core_Action
::replace($link['qs'], $ids)
863 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
865 CRM_Utils_Array
::value('title', $link),
871 $extraLinksName = strtolower($extraULName);
873 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
874 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
875 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
882 * Retrieve survey associated profile id.
885 public static function getSurveyProfileId($surveyId) {
890 static $ufIds = array();
891 if (!array_key_exists($surveyId, $ufIds)) {
892 //get the profile id.
893 $ufJoinParams = array(
894 'entity_id' => $surveyId,
895 'entity_table' => 'civicrm_survey',
896 'module' => 'CiviCampaign',
899 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
902 $ufIds[$surveyId] = array($first);
905 $ufIds[$surveyId][] = array_shift($second);
909 return CRM_Utils_Array
::value($surveyId, $ufIds);
913 * @param int $surveyId
917 public Static function getReportID($surveyId) {
918 static $reportIds = array();
920 if (!array_key_exists($surveyId, $reportIds)) {
921 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
922 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
923 $reportIds[$surveyId] = $reportID;
925 return $reportIds[$surveyId];
929 * Decides the contact type for given survey.
932 public static function getSurveyContactType($surveyId) {
935 //apply filter of profile type on search.
936 $profileId = self
::getSurveyProfileId($surveyId);
938 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
939 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
940 $contactType = $profileType;
948 * Get survey supportable profile types
951 public static function surveyProfileTypes() {
952 static $profileTypes;
954 if (!isset($profileTypes)) {
955 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
956 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
959 return $profileTypes;
963 * Get the valid survey response fields those
964 * are configured with profile and custom fields.
966 * @param int $surveyId
968 * @param int $surveyTypeId
969 * Survey activity type id.
971 * @return array an array of valid survey response fields.
973 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
974 if (empty($surveyId)) {
978 static $responseFields;
979 $cacheKey = "{$surveyId}_{$surveyTypeId}";
981 if (isset($responseFields[$cacheKey])) {
982 return $responseFields[$cacheKey];
985 $responseFields[$cacheKey] = array();
987 $profileId = self
::getSurveyProfileId($surveyId);
990 return $responseFields;
993 if (!$surveyTypeId) {
994 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
997 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
998 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
1001 //don't load these fields in grid.
1002 $removeFields = array('File', 'RichTextEditor');
1004 $supportableFieldTypes = self
::surveyProfileTypes();
1006 // get custom fields of type survey
1007 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
1009 foreach ($profileFields as $name => $field) {
1010 //get only contact and activity fields.
1011 //later stage we might going to consider contact type also.
1012 if (in_array($field['field_type'], $supportableFieldTypes)) {
1013 // we should allow all supported custom data for survey
1014 // In case of activity, allow normal activity and with subtype survey,
1015 // suppress custom data of other activity types
1016 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1017 if (!in_array($field['html_type'], $removeFields)) {
1018 if ($field['field_type'] != 'Activity') {
1019 $responseFields[$cacheKey][$name] = $field;
1021 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1022 $responseFields[$cacheKey][$name] = $field;
1027 $responseFields[$cacheKey][$name] = $field;
1032 return $responseFields[$cacheKey];
1036 * Get all interviewers of surveys.
1038 * @return array an array of valid survey response fields.
1040 public static function getInterviewers() {
1041 static $interviewers;
1043 if (isset($interviewers)) {
1044 return $interviewers;
1047 $whereClause = NULL;
1048 $activityTypes = self
::getSurveyActivityType();
1049 if (!empty($activityTypes)) {
1050 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1053 $interviewers = array();
1054 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1055 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1058 SELECT contact.id as id,
1059 contact.sort_name as sort_name
1060 FROM civicrm_contact contact
1061 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1062 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1063 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1066 $interviewer = CRM_Core_DAO
::executeQuery($query);
1067 while ($interviewer->fetch()) {
1068 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1071 return $interviewers;
1075 * Check and update the survey respondents.
1077 * @param array $params
1079 * @return array success message
1081 public static function releaseRespondent($params) {
1082 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1083 $reserveStatusId = array_search('Scheduled', $activityStatus);
1084 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1085 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1086 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1089 //retrieve all survey activities related to reserve action.
1091 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1093 SELECT activity.id as id,
1094 activity.activity_date_time as activity_date_time,
1095 survey.id as surveyId,
1096 survey.release_frequency as release_frequency
1097 FROM civicrm_activity activity
1098 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1099 WHERE activity.is_deleted = 0
1100 AND activity.status_id = %1
1101 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1102 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1103 $releasedIds = array();
1104 while ($activity->fetch()) {
1105 if (!$activity->release_frequency
) {
1108 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1109 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1110 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1111 if ($totalReservedSeconds < time()) {
1112 $releasedIds[$activity->id
] = $activity->id
;
1116 //released respondent.
1117 if (!empty($releasedIds)) {
1119 UPDATE civicrm_activity
1121 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1122 CRM_Core_DAO
::executeQuery($query);
1123 $releasedCount = count($releasedIds);
1129 'messages' => "Number of respondents released = {$releasedCount}",
1136 * Get options for a given field.
1137 * @see CRM_Core_DAO::buildOptions
1139 * @param string $fieldName
1140 * @param string $context: @see CRM_Core_DAO::buildOptionsContext
1141 * @param array $props: whatever is known about this dao object
1143 * @return array|bool
1145 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1147 // Special logic for fields whose options depend on context or properties
1148 switch ($fieldName) {
1149 case 'activity_type_id':
1150 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1151 if ($campaignCompId) {
1152 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1156 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);