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 $surveyTypes
345 * Array 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.@static
523 static function voterActivityDetails(
524 $surveyId, $voterIds, $interviewerId = NULL,
525 $statusIds = array()) {
526 $activityDetails = array();
528 !is_array($voterIds) ||
empty($voterIds)
530 return $activityDetails;
534 if (is_array($statusIds) && !empty($statusIds)) {
535 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
538 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
539 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
540 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
541 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
543 $params[1] = array($surveyId, 'Integer');
545 SELECT activity.id, activity.status_id,
546 activityTarget.contact_id as voter_id,
547 activityAssignment.contact_id as interviewer_id
548 FROM civicrm_activity activity
549 INNER JOIN civicrm_activity_contact activityTarget
550 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
551 INNER JOIN civicrm_activity_contact activityAssignment
552 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
553 WHERE activity.source_record_id = %1
554 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
555 if (!empty($interviewerId)) {
556 $query .= "AND activityAssignment.contact_id = %2 ";
557 $params[2] = array($interviewerId, 'Integer');
559 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
561 $activity = CRM_Core_DAO
::executeQuery($query, $params);
562 while ($activity->fetch()) {
563 $activityDetails[$activity->voter_id
] = array(
564 'voter_id' => $activity->voter_id
,
565 'status_id' => $activity->status_id
,
566 'activity_id' => $activity->id
,
567 'interviewer_id' => $activity->interviewer_id
,
571 return $activityDetails;
575 * This function retrieve survey related activities.
577 * @param int $surveyId
580 * @param int $interviewerId
581 * @param null $statusIds
582 * @param null $voterIds
583 * @param bool $onlyCount
584 * @return array $activities an array of survey activity.@static
586 static function getSurveyActivities(
588 $interviewerId = NULL,
593 $activities = array();
594 $surveyActivityCount = 0;
596 return ($onlyCount) ?
0 : $activities;
600 if (!empty($statusIds)) {
601 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
604 if ($interviewerId) {
605 $where[] = "( activityAssignment.contact_id = $interviewerId )";
608 if (!empty($voterIds)) {
609 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
613 if (!empty($where)) {
614 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
617 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
623 $select = "SELECT count(activity.id)";
627 SELECT activity.id, activity.status_id,
628 activityTarget.contact_id as voter_id,
629 activityAssignment.contact_id as interviewer_id,
630 activity.result as result,
631 activity.activity_date_time as activity_date_time,
632 contact_a.display_name as voter_name";
635 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
636 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
637 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
641 FROM civicrm_activity activity
642 INNER JOIN civicrm_activity_contact activityTarget
643 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
644 INNER JOIN civicrm_activity_contact activityAssignment
645 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
646 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
647 WHERE activity.source_record_id = %1
648 AND activity.activity_type_id = %2
649 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
653 1 => array($surveyId, 'Integer'),
654 2 => array($actTypeId, 'Integer'),
658 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
659 return ($dbCount) ?
$dbCount : 0;
662 $activity = CRM_Core_DAO
::executeQuery($query, $params);
664 while ($activity->fetch()) {
665 $activities[$activity->id
] = array(
666 'id' => $activity->id
,
667 'voter_id' => $activity->voter_id
,
668 'voter_name' => $activity->voter_name
,
669 'status_id' => $activity->status_id
,
670 'interviewer_id' => $activity->interviewer_id
,
671 'result' => $activity->result
,
672 'activity_date_time' => $activity->activity_date_time
680 * This function retrieve survey voter information.
682 * @param int $surveyId
684 * @param int $interviewerId
686 * @param array $statusIds
689 * @return array $$contactIds survey related contact ids.
692 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
698 $cacheKey = $surveyId;
699 if ($interviewerId) {
700 $cacheKey .= "_{$interviewerId}";
702 if (is_array($statusIds) && !empty($statusIds)) {
703 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
706 static $contactIds = array();
707 if (!isset($contactIds[$cacheKey])) {
708 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
709 foreach ($activities as $values) {
710 $voterIds[$values['voter_id']] = $values;
712 $contactIds[$cacheKey] = $voterIds;
715 return $contactIds[$cacheKey];
719 * This function retrieve all option groups which are created as a result set
721 * @param string $valueColumnName
722 * @return array $resultSets an array of option groups.@static
724 public static function getResultSets($valueColumnName = 'title') {
725 $resultSets = array();
726 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
728 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
729 $dao = CRM_Core_DAO
::executeQuery($query);
730 while ($dao->fetch()) {
731 $resultSets[$dao->id
] = $dao->$valueColumnName;
738 * This function is to check survey activity.
740 * @param int $activityId
742 * @return boolean $isSurveyActivity true/false
745 public static function isSurveyActivity($activityId) {
746 $isSurveyActivity = FALSE;
748 return $isSurveyActivity;
751 $activity = new CRM_Activity_DAO_Activity();
752 $activity->id
= $activityId;
753 $activity->selectAdd('source_record_id, activity_type_id');
754 if ($activity->find(TRUE) &&
755 $activity->source_record_id
757 $surveyActTypes = self
::getSurveyActivityType();
758 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
759 $isSurveyActivity = TRUE;
763 return $isSurveyActivity;
767 * This function retrive all response options of survey
769 * @param int $surveyId
771 * @return array $responseOptions an array of option values@static
773 public static function getResponsesOptions($surveyId) {
774 $responseOptions = array();
776 return $responseOptions;
779 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
781 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
784 return $responseOptions;
788 * This function return all voter links with respecting permissions
790 * @param int $surveyId
791 * @param bool $enclosedInUL
792 * @param string $extraULName
793 * @return array|string $url array of permissioned links@static
795 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
796 $menuLinks = array();
801 static $voterLinks = array();
802 if (empty($voterLinks)) {
803 $permissioned = FALSE;
804 if (CRM_Core_Permission
::check('manage campaign') ||
805 CRM_Core_Permission
::check('administer CiviCampaign')
807 $permissioned = TRUE;
810 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
811 $voterLinks['reserve'] = array(
813 'url' => 'civicrm/survey/search',
814 'qs' => 'sid=%%id%%&reset=1&op=reserve',
815 'title' => ts('Reserve Respondents'),
818 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
819 $voterLinks['release'] = array(
820 'name' => 'interview',
821 'url' => 'civicrm/survey/search',
822 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
823 'title' => ts('Interview Respondents'),
826 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
827 $voterLinks['interview'] = array(
829 'url' => 'civicrm/survey/search',
830 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
831 'title' => ts('Release Respondents'),
836 if (CRM_Core_Permission
::check('access CiviReport')) {
837 $reportID = self
::getReportID($surveyId);
839 $voterLinks['report'] =
842 'url' => "civicrm/report/instance/{$reportID}",
844 'title' => ts('View Survey Report'),
849 $ids = array('id' => $surveyId);
850 foreach ($voterLinks as $link) {
851 if (!empty($link['qs']) &&
852 !CRM_Utils_System
::isNull($link['qs'])
854 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
855 CRM_Core_Action
::replace($link['qs'], $ids)
857 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
859 CRM_Utils_Array
::value('title', $link),
865 $extraLinksName = strtolower($extraULName);
867 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
868 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
869 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
876 * Retrieve survey associated profile id.
879 public static function getSurveyProfileId($surveyId) {
884 static $ufIds = array();
885 if (!array_key_exists($surveyId, $ufIds)) {
886 //get the profile id.
887 $ufJoinParams = array(
888 'entity_id' => $surveyId,
889 'entity_table' => 'civicrm_survey',
890 'module' => 'CiviCampaign',
893 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
896 $ufIds[$surveyId] = array($first);
899 $ufIds[$surveyId][] = array_shift($second);
903 return CRM_Utils_Array
::value($surveyId, $ufIds);
907 * @param int $surveyId
911 public Static function getReportID($surveyId) {
912 static $reportIds = array();
914 if (!array_key_exists($surveyId, $reportIds)) {
915 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
916 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
917 $reportIds[$surveyId] = $reportID;
919 return $reportIds[$surveyId];
923 * Decides the contact type for given survey.
926 public static function getSurveyContactType($surveyId) {
929 //apply filter of profile type on search.
930 $profileId = self
::getSurveyProfileId($surveyId);
932 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
933 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
934 $contactType = $profileType;
942 * Get survey supportable profile types
945 public static function surveyProfileTypes() {
946 static $profileTypes;
948 if (!isset($profileTypes)) {
949 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
950 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
953 return $profileTypes;
957 * Get the valid survey response fields those
958 * are configured with profile and custom fields.
960 * @param int $surveyId
962 * @param int $surveyTypeId
963 * Survey activity type id.
965 * @return array an array of valid survey response fields.
967 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
968 if (empty($surveyId)) {
972 static $responseFields;
973 $cacheKey = "{$surveyId}_{$surveyTypeId}";
975 if (isset($responseFields[$cacheKey])) {
976 return $responseFields[$cacheKey];
979 $responseFields[$cacheKey] = array();
981 $profileId = self
::getSurveyProfileId($surveyId);
984 return $responseFields;
987 if (!$surveyTypeId) {
988 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
991 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
992 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
995 //don't load these fields in grid.
996 $removeFields = array('File', 'RichTextEditor');
998 $supportableFieldTypes = self
::surveyProfileTypes();
1000 // get custom fields of type survey
1001 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
1003 foreach ($profileFields as $name => $field) {
1004 //get only contact and activity fields.
1005 //later stage we might going to consider contact type also.
1006 if (in_array($field['field_type'], $supportableFieldTypes)) {
1007 // we should allow all supported custom data for survey
1008 // In case of activity, allow normal activity and with subtype survey,
1009 // suppress custom data of other activity types
1010 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
1011 if (!in_array($field['html_type'], $removeFields)) {
1012 if ($field['field_type'] != 'Activity') {
1013 $responseFields[$cacheKey][$name] = $field;
1015 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1016 $responseFields[$cacheKey][$name] = $field;
1021 $responseFields[$cacheKey][$name] = $field;
1026 return $responseFields[$cacheKey];
1030 * Get all interviewers of surveys.
1032 * @return array an array of valid survey response fields.
1034 public static function getInterviewers() {
1035 static $interviewers;
1037 if (isset($interviewers)) {
1038 return $interviewers;
1041 $whereClause = NULL;
1042 $activityTypes = self
::getSurveyActivityType();
1043 if (!empty($activityTypes)) {
1044 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1047 $interviewers = array();
1048 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1049 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1052 SELECT contact.id as id,
1053 contact.sort_name as sort_name
1054 FROM civicrm_contact contact
1055 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1056 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1057 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1060 $interviewer = CRM_Core_DAO
::executeQuery($query);
1061 while ($interviewer->fetch()) {
1062 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1065 return $interviewers;
1069 * Check and update the survey respondents.
1071 * @param array $params
1073 * @return array success message
1075 public static function releaseRespondent($params) {
1076 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1077 $reserveStatusId = array_search('Scheduled', $activityStatus);
1078 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1079 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1080 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1083 //retrieve all survey activities related to reserve action.
1085 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1087 SELECT activity.id as id,
1088 activity.activity_date_time as activity_date_time,
1089 survey.id as surveyId,
1090 survey.release_frequency as release_frequency
1091 FROM civicrm_activity activity
1092 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1093 WHERE activity.is_deleted = 0
1094 AND activity.status_id = %1
1095 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1096 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1097 $releasedIds = array();
1098 while ($activity->fetch()) {
1099 if (!$activity->release_frequency
) {
1102 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1103 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1104 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1105 if ($totalReservedSeconds < time()) {
1106 $releasedIds[$activity->id
] = $activity->id
;
1110 //released respondent.
1111 if (!empty($releasedIds)) {
1113 UPDATE civicrm_activity
1115 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1116 CRM_Core_DAO
::executeQuery($query);
1117 $releasedCount = count($releasedIds);
1123 'messages' => "Number of respondents released = {$releasedCount}",
1130 * Get options for a given field.
1131 * @see CRM_Core_DAO::buildOptions
1133 * @param string $fieldName
1134 * @param string $context: @see CRM_Core_DAO::buildOptionsContext
1135 * @param array $props: whatever is known about this dao object
1137 * @return array|bool
1139 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1141 // Special logic for fields whose options depend on context or properties
1142 switch ($fieldName) {
1143 case 'activity_type_id':
1144 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1145 if ($campaignCompId) {
1146 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1150 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);