3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 (reference ) an assoc array of name/value pairs
48 * @param array $defaults (reference ) an assoc array to hold the flattened values
54 * The action links that we need to display for the browse screen
59 * @return \CRM_Campaign_DAO_Survey|null
60 * @internal param array $
62 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
83 * @return object CRM_Survey_DAO_Survey object
87 static function create(&$params) {
92 if (!empty($params['is_default'])) {
93 $query = "UPDATE civicrm_survey SET is_default = 0";
94 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
97 if (!(CRM_Utils_Array
::value('id', $params))) {
99 if (!(CRM_Utils_Array
::value('created_id', $params))) {
100 $session = CRM_Core_Session
::singleton();
101 $params['created_id'] = $session->get('userID');
103 if (!(CRM_Utils_Array
::value('created_date', $params))) {
104 $params['created_date'] = date('YmdHis');
108 $dao = new CRM_Campaign_DAO_Survey();
109 $dao->copyValues($params);
112 if (!empty($params['custom']) &&
113 is_array($params['custom'])
115 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_survey', $dao->id
);
121 * Function to retrieve surveys for dashboard.
125 static function getSurveySummary($params = array(
126 ), $onlyCount = FALSE) {
127 //build the limit and order clause.
128 $limitClause = $orderByClause = $lookupTableJoins = NULL;
131 'sort' => 'created_date',
134 'sortOrder' => 'desc',
136 foreach ($sortParams as $name => $default) {
137 if (!empty($params[$name])) {
138 $sortParams[$name] = $params[$name];
142 //need to lookup tables.
143 $orderOnSurveyTable = TRUE;
144 if ($sortParams['sort'] == 'campaign') {
145 $orderOnSurveyTable = FALSE;
146 $lookupTableJoins = '
147 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
148 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
150 elseif ($sortParams['sort'] == 'activity_type') {
151 $orderOnSurveyTable = FALSE;
152 $lookupTableJoins = "
153 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
154 OR survey.activity_type_id IS NULL )
155 INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
156 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
158 elseif ($sortParams['sort'] == 'isActive') {
159 $sortParams['sort'] = 'is_active';
161 if ($orderOnSurveyTable) {
162 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
164 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
167 //build the where clause.
168 $queryParams = $where = array();
170 //we only have activity type as a
171 //difference between survey and petition.
172 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
173 if ($petitionTypeID) {
174 $where[] = "( survey.activity_type_id != %1 )";
175 $queryParams[1] = array($petitionTypeID, 'Positive');
178 if (!empty($params['title'])) {
179 $where[] = "( survey.title LIKE %2 )";
180 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
182 if (!empty($params['campaign_id'])) {
183 $where[] = '( survey.campaign_id = %3 )';
184 $queryParams[3] = array($params['campaign_id'], 'Positive');
186 if (!empty($params['activity_type_id'])) {
187 $typeId = $params['activity_type_id'];
188 if (is_array($params['activity_type_id'])) {
189 $typeId = implode(' , ', $params['activity_type_id']);
191 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
194 if (!empty($where)) {
195 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
199 SELECT survey.id as id,
200 survey.title as title,
201 survey.is_active as is_active,
202 survey.result_id as result_id,
203 survey.is_default as is_default,
204 survey.campaign_id as campaign_id,
205 survey.activity_type_id as activity_type_id,
206 survey.release_frequency as release_frequency,
207 survey.max_number_of_contacts as max_number_of_contacts,
208 survey.default_number_of_contacts as default_number_of_contacts';
210 $selectClause = 'SELECT COUNT(*)';
212 $fromClause = 'FROM civicrm_survey survey';
214 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
218 return (int)CRM_Core_DAO
::singleValueQuery($query, $queryParams);
223 'id', 'title', 'campaign_id', 'is_active', 'is_default', 'result_id', 'activity_type_id',
224 'release_frequency', 'max_number_of_contacts', 'default_number_of_contacts',
227 $survey = CRM_Core_DAO
::executeQuery($query, $queryParams);
228 while ($survey->fetch()) {
229 foreach ($properties as $property) {
230 $surveys[$survey->id
][$property] = $survey->$property;
238 * Get the survey count.
242 static function getSurveyCount() {
243 return (int)CRM_Core_DAO
::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
247 * Function to get Surveys
249 * @param boolean $onlyActive retrieve only active surveys.
250 * @param boolean $onlyDefault retrieve only default survey.
251 * @param boolean $forceAll retrieve all surveys.
252 * @param boolean $includePetition include or exclude petitions
256 static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE ) {
258 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
259 foreach ($cacheKeyParams as $param) {
260 $cacheParam = $
$param;
264 $cacheKey .= '_' . $cacheParam;
269 if (!isset($surveys[$cacheKey])) {
270 if (!$includePetition) {
271 //we only have activity type as a
272 //difference between survey and petition.
273 $petitionTypeID = CRM_Core_OptionGroup
::getValue('activity_type', 'petition', 'name');
276 if ($petitionTypeID) {
277 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
280 if (!$forceAll && $onlyActive) {
281 $where[] = '( survey.is_active = 1 )';
283 if (!$forceAll && $onlyDefault) {
284 $where[] = '( survey.is_default = 1 )';
286 $whereClause = implode(' AND ', $where);
289 SELECT survey.id as id,
290 survey.title as title
291 FROM civicrm_survey as survey
292 WHERE {$whereClause}";
293 $surveys[$cacheKey] = array();
294 $survey = CRM_Core_DAO
::executeQuery($query);
295 while ($survey->fetch()) {
296 $surveys[$cacheKey][$survey->id
] = $survey->title
;
300 return $surveys[$cacheKey];
304 * Function to get Surveys activity types
309 static function getSurveyActivityType($returnColumn = 'label',
310 $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 * Function to get Surveys custom groups
341 * @param $surveyTypes array an array of survey type id.
346 static function getSurveyCustomGroups($surveyTypes = array(
348 $customGroups = array();
349 if (!is_array($surveyTypes)) {
350 $surveyTypes = array($surveyTypes);
353 if (!empty($surveyTypes)) {
354 $activityTypes = array_flip($surveyTypes);
357 $activityTypes = self
::getSurveyActivityType();
360 if (!empty($activityTypes)) {
361 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
363 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
364 FROM civicrm_custom_group cg
365 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
367 $dao = CRM_Core_DAO
::executeQuery($query);
368 while ($dao->fetch()) {
369 $customGroups[$dao->id
]['id'] = $dao->id
;
370 $customGroups[$dao->id
]['name'] = $dao->name
;
371 $customGroups[$dao->id
]['title'] = $dao->title
;
372 $customGroups[$dao->id
]['extends'] = $dao->extends_entity_column_value
;
376 return $customGroups;
380 * update the is_active flag in the db
382 * @param int $id id of the database record
383 * @param boolean $is_active value we want to set the is_active field
385 * @return Object DAO object on sucess, null otherwise
388 static function setIsActive($id, $is_active) {
389 return CRM_Core_DAO
::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
393 * Function to delete the survey
395 * @param int $id survey id
402 static function del($id) {
406 $reportId = CRM_Campaign_BAO_Survey
::getReportID($id);
408 CRM_Report_BAO_ReportInstance
::del($reportId);
410 $dao = new CRM_Campaign_DAO_Survey();
412 return $dao->delete();
416 * This function retrieve contact information.
419 * @param array $returnProperties an array of return elements.
421 * @internal param array $voter an array of contact Ids.
422 * @return array $voterDetails array of contact info.@static
424 static function voterDetails($voterIds, $returnProperties = array(
426 $voterDetails = array();
427 if (!is_array($voterIds) ||
empty($voterIds)) {
428 return $voterDetails;
431 if (empty($returnProperties)) {
432 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
433 'contact_autocomplete_options'
435 $returnProperties = array_fill_keys(array_merge(array(
440 array_keys($autocompleteContactSearch)
444 $select = $from = array();
445 foreach ($returnProperties as $property => $ignore) {
446 $value = (in_array($property, array(
447 'city', 'street_address'))) ?
'address' : $property;
451 case 'contact_sub_type':
452 $select[] = "$property as $property";
453 $from['contact'] = 'civicrm_contact contact';
459 case 'street_address':
460 $select[] = "$property as $property";
461 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
465 case 'state_province':
466 $select[] = "{$property}.name as $property";
467 if (!in_array('address', $from)) {
468 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
470 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
475 //finally retrieve contact details.
476 if (!empty($select) && !empty($from)) {
477 $fromClause = implode(' ', $from);
478 $selectClause = implode(', ', $select);
479 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
482 SELECT contact.id as contactId, $selectClause
485 Group By contact.id";
487 $contact = CRM_Core_DAO
::executeQuery($query);
488 while ($contact->fetch()) {
489 $voterDetails[$contact->contactId
]['contact_id'] = $contact->contactId
;
490 foreach ($returnProperties as $property => $ignore) {
491 $voterDetails[$contact->contactId
][$property] = $contact->$property;
493 $image = CRM_Contact_BAO_Contact_Utils
::getImage($contact->contact_sub_type ?
494 $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 survey id.
510 * @param array $voterIds voterIds.
512 * @param null $interviewerId
513 * @param array $statusIds
515 * @return array $activityDetails array of survey activity.@static
517 static function voterActivityDetails($surveyId, $voterIds, $interviewerId = NULL,
518 $statusIds = array()) {
519 $activityDetails = array();
521 !is_array($voterIds) ||
empty($voterIds)
523 return $activityDetails;
527 if (is_array($statusIds) && !empty($statusIds)) {
528 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
531 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
532 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
533 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
534 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
536 $params[1] = array($surveyId, 'Integer');
538 SELECT activity.id, activity.status_id,
539 activityTarget.contact_id as voter_id,
540 activityAssignment.contact_id as interviewer_id
541 FROM civicrm_activity activity
542 INNER JOIN civicrm_activity_contact activityTarget
543 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
544 INNER JOIN civicrm_activity_contact activityAssignment
545 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
546 WHERE activity.source_record_id = %1
547 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
548 if(!empty($interviewerId)) {
549 $query .= "AND activityAssignment.contact_id = %2 ";
550 $params[2] = array($interviewerId, 'Integer');
552 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
554 $activity = CRM_Core_DAO
::executeQuery($query, $params);
555 while ($activity->fetch()) {
556 $activityDetails[$activity->voter_id
] = array(
557 'voter_id' => $activity->voter_id
,
558 'status_id' => $activity->status_id
,
559 'activity_id' => $activity->id
,
560 'interviewer_id' => $activity->interviewer_id
,
564 return $activityDetails;
568 * This function retrieve survey related activities.
570 * @param int $surveyId survey id.
572 * @param null $interviewerId
573 * @param null $statusIds
574 * @param null $voterIds
575 * @param bool $onlyCount
576 * @return array $activities an array of survey activity.@static
578 static function getSurveyActivities($surveyId,
579 $interviewerId = NULL,
584 $activities = array();
585 $surveyActivityCount = 0;
587 return ($onlyCount) ?
0 : $activities;
591 if (!empty($statusIds)) {
592 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
595 if ($interviewerId) {
596 $where[] = "( activityAssignment.contact_id = $interviewerId )";
599 if (!empty($voterIds)) {
600 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
604 if (!empty($where)) {
605 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
608 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
614 $select = "SELECT count(activity.id)";
618 SELECT activity.id, activity.status_id,
619 activityTarget.contact_id as voter_id,
620 activityAssignment.contact_id as interviewer_id,
621 activity.result as result,
622 activity.activity_date_time as activity_date_time,
623 contact_a.display_name as voter_name";
626 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
627 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
628 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
632 FROM civicrm_activity activity
633 INNER JOIN civicrm_activity_contact activityTarget
634 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
635 INNER JOIN civicrm_activity_contact activityAssignment
636 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
637 INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
638 WHERE activity.source_record_id = %1
639 AND activity.activity_type_id = %2
640 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
643 $params = array(1 => array($surveyId, 'Integer'),
644 2 => array($actTypeId, 'Integer'),
648 $dbCount = CRM_Core_DAO
::singleValueQuery($query, $params);
649 return ($dbCount) ?
$dbCount : 0;
652 $activity = CRM_Core_DAO
::executeQuery($query, $params);
654 while ($activity->fetch()) {
655 $activities[$activity->id
] = array(
656 'id' => $activity->id
,
657 'voter_id' => $activity->voter_id
,
658 'voter_name' => $activity->voter_name
,
659 'status_id' => $activity->status_id
,
660 'interviewer_id' => $activity->interviewer_id
,
661 'result' => $activity->result
,
662 'activity_date_time' => $activity->activity_date_time
670 * This function retrieve survey voter information.
672 * @param int $surveyId survey id.
673 * @param int $interviewerId interviewer id.
674 * @param array $statusIds survey status ids.
676 * @return array $$contactIds survey related contact ids.
679 static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array( )) {
685 $cacheKey = $surveyId;
686 if ($interviewerId) {
687 $cacheKey .= "_{$interviewerId}";
689 if (is_array($statusIds) && !empty($statusIds)) {
690 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
693 static $contactIds = array();
694 if (!isset($contactIds[$cacheKey])) {
695 $activities = self
::getSurveyActivities($surveyId, $interviewerId, $statusIds);
696 foreach ($activities as $values) {
697 $voterIds[$values['voter_id']] = $values;
699 $contactIds[$cacheKey] = $voterIds;
702 return $contactIds[$cacheKey];
706 * This function retrieve all option groups which are created as a result set
708 * @param string $valueColumnName
709 * @return array $resultSets an array of option groups.@static
711 static function getResultSets( $valueColumnName = 'title' ) {
712 $resultSets = array();
713 $valueColumnName = CRM_Utils_Type
::escape($valueColumnName, 'String');
715 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
716 $dao = CRM_Core_DAO
::executeQuery($query);
717 while ($dao->fetch()) {
718 $resultSets[$dao->id
] = $dao->$valueColumnName;
725 * This function is to check survey activity.
727 * @param int $activityId activity id.
728 * @internal param int $activityTypeId activity type id.
729 * @return boolean $isSurveyActivity true/false boolean.
732 static function isSurveyActivity($activityId) {
733 $isSurveyActivity = FALSE;
735 return $isSurveyActivity;
738 $activity = new CRM_Activity_DAO_Activity();
739 $activity->id
= $activityId;
740 $activity->selectAdd('source_record_id, activity_type_id');
741 if ($activity->find(TRUE) &&
742 $activity->source_record_id
744 $surveyActTypes = self
::getSurveyActivityType();
745 if (array_key_exists($activity->activity_type_id
, $surveyActTypes)) {
746 $isSurveyActivity = TRUE;
750 return $isSurveyActivity;
754 * This function retrive all response options of survey
756 * @param int $surveyId survey id.
757 * @return array $responseOptions an array of option values@static
759 static function getResponsesOptions($surveyId) {
760 $responseOptions = array();
762 return $responseOptions;
765 $resultId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
767 $responseOptions = CRM_Core_OptionGroup
::valuesByID($resultId);
770 return $responseOptions;
774 * This function return all voter links with respecting permissions
777 * @param bool $enclosedInUL
778 * @param string $extraULName
779 * @return array|string $url array of permissioned links@static
781 static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
782 $menuLinks = array();
787 static $voterLinks = array();
788 if (empty($voterLinks)) {
789 $permissioned = FALSE;
790 if (CRM_Core_Permission
::check('manage campaign') ||
791 CRM_Core_Permission
::check('administer CiviCampaign')
793 $permissioned = TRUE;
796 if ($permissioned || CRM_Core_Permission
::check("reserve campaign contacts")) {
797 $voterLinks['reserve'] = array(
799 'url' => 'civicrm/survey/search',
800 'qs' => 'sid=%%id%%&reset=1&op=reserve',
801 'title' => ts('Reserve Respondents'),
804 if ($permissioned || CRM_Core_Permission
::check("interview campaign contacts")) {
805 $voterLinks['release'] = array(
806 'name' => 'interview',
807 'url' => 'civicrm/survey/search',
808 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
809 'title' => ts('Interview Respondents'),
812 if ($permissioned || CRM_Core_Permission
::check("release campaign contacts")) {
813 $voterLinks['interview'] = array(
815 'url' => 'civicrm/survey/search',
816 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
817 'title' => ts('Release Respondents'),
822 if (CRM_Core_Permission
::check('access CiviReport')) {
823 $reportID = self
::getReportID($surveyId);
825 $voterLinks['report'] =
828 'url' => "civicrm/report/instance/{$reportID}",
830 'title' => ts('View Survey Report'),
835 $ids = array('id' => $surveyId);
836 foreach ($voterLinks as $link) {
837 if (!empty($link['qs']) &&
838 !CRM_Utils_System
::isNull($link['qs'])
840 $urlPath = CRM_Utils_System
::url(CRM_Core_Action
::replace($link['url'], $ids),
841 CRM_Core_Action
::replace($link['qs'], $ids)
843 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
845 CRM_Utils_Array
::value('title', $link),
851 $extraLinksName = strtolower($extraULName);
853 CRM_Utils_String
::append($allLinks, '</li><li>', $menuLinks);
854 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
855 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
862 * Function to retrieve survey associated profile id.
865 public static function getSurveyProfileId($surveyId) {
870 static $ufIds = array();
871 if (!array_key_exists($surveyId, $ufIds)) {
872 //get the profile id.
873 $ufJoinParams = array(
874 'entity_id' => $surveyId,
875 'entity_table' => 'civicrm_survey',
876 'module' => 'CiviCampaign',
879 list($first, $second) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
882 $ufIds[$surveyId] = array($first);
885 $ufIds[$surveyId][] = array_shift($second);
889 return CRM_Utils_Array
::value($surveyId, $ufIds);
897 public Static function getReportID($surveyId) {
898 static $reportIds = array();
900 if (!array_key_exists($surveyId, $reportIds)) {
901 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
902 $reportID = CRM_Core_DAO
::singleValueQuery($query, array(1 => array("survey_{$surveyId}",'String')));
903 $reportIds[$surveyId] = $reportID;
905 return $reportIds[$surveyId];
909 * Function to decides the contact type for given survey.
912 public static function getSurveyContactType($surveyId) {
915 //apply filter of profile type on search.
916 $profileId = self
::getSurveyProfileId($surveyId);
918 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
919 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
920 $contactType = $profileType;
928 * Function to get survey supportable profile types
931 public static function surveyProfileTypes() {
932 static $profileTypes;
934 if (!isset($profileTypes)) {
935 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
936 $profileTypes = array_diff($profileTypes, array('Organization','Household'));
939 return $profileTypes;
943 * Get the valid survey response fields those
944 * are configured with profile and custom fields.
946 * @param int $surveyId survey id.
947 * @param int $surveyTypeId survey activity type id.
949 * @return array an array of valid survey response fields.
951 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
952 if (empty($surveyId)) {
956 static $responseFields;
957 $cacheKey = "{$surveyId}_{$surveyTypeId}";
959 if (isset($responseFields[$cacheKey])) {
960 return $responseFields[$cacheKey];
963 $responseFields[$cacheKey] = array();
965 $profileId = self
::getSurveyProfileId($surveyId);
968 return $responseFields;
971 if (!$surveyTypeId) {
972 $surveyTypeId = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
975 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileId,
976 FALSE, CRM_Core_Action
::VIEW
, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission
::CREATE
, 'field_name', TRUE
979 //don't load these fields in grid.
980 $removeFields = array('File', 'RichTextEditor');
982 $supportableFieldTypes = self
::surveyProfileTypes();
984 // get custom fields of type survey
985 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $surveyTypeId);
987 foreach ($profileFields as $name => $field) {
988 //get only contact and activity fields.
989 //later stage we might going to consider contact type also.
990 if (in_array($field['field_type'], $supportableFieldTypes)) {
991 // we should allow all supported custom data for survey
992 // In case of activity, allow normal activity and with subtype survey,
993 // suppress custom data of other activity types
994 if (CRM_Core_BAO_CustomField
::getKeyID($name)) {
995 if (!in_array($field['html_type'], $removeFields)) {
996 if ($field['field_type'] != 'Activity') {
997 $responseFields[$cacheKey][$name] = $field;
999 elseif (array_key_exists(CRM_Core_BAO_CustomField
::getKeyID($name), $customFields)) {
1000 $responseFields[$cacheKey][$name] = $field;
1005 $responseFields[$cacheKey][$name] = $field;
1010 return $responseFields[$cacheKey];
1014 * Get all interviewers of surveys.
1016 * @return array an array of valid survey response fields.
1018 public static function getInterviewers() {
1019 static $interviewers;
1021 if (isset($interviewers)) {
1022 return $interviewers;
1025 $whereClause = NULL;
1026 $activityTypes = self
::getSurveyActivityType();
1027 if (!empty($activityTypes)) {
1028 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1031 $interviewers = array();
1032 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1033 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1036 SELECT contact.id as id,
1037 contact.sort_name as sort_name
1038 FROM civicrm_contact contact
1039 INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
1040 INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1041 INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1044 $interviewer = CRM_Core_DAO
::executeQuery($query);
1045 while ($interviewer->fetch()) {
1046 $interviewers[$interviewer->id
] = $interviewer->sort_name
;
1049 return $interviewers;
1053 * Check and update the survey respondents.
1057 * @return array success message
1059 public static function releaseRespondent($params) {
1060 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
1061 $reserveStatusId = array_search('Scheduled', $activityStatus);
1062 $surveyActivityTypes = CRM_Campaign_BAO_Survey
::getSurveyActivityType();
1063 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1064 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1067 //retrieve all survey activities related to reserve action.
1069 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1071 SELECT activity.id as id,
1072 activity.activity_date_time as activity_date_time,
1073 survey.id as surveyId,
1074 survey.release_frequency as release_frequency
1075 FROM civicrm_activity activity
1076 INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1077 WHERE activity.is_deleted = 0
1078 AND activity.status_id = %1
1079 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1080 $activity = CRM_Core_DAO
::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1081 $releasedIds = array();
1082 while ($activity->fetch()) {
1083 if (!$activity->release_frequency
) {
1086 $reservedSeconds = CRM_Utils_Date
::unixTime($activity->activity_date_time
);
1087 $releasedSeconds = $activity->release_frequency
* 24 * 3600;
1088 $totalReservedSeconds = $reservedSeconds +
$releasedSeconds;
1089 if ($totalReservedSeconds < time()) {
1090 $releasedIds[$activity->id
] = $activity->id
;
1094 //released respondent.
1095 if (!empty($releasedIds)) {
1097 UPDATE civicrm_activity
1099 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1100 CRM_Core_DAO
::executeQuery($query);
1101 $releasedCount = count($releasedIds);
1107 'messages' => "Number of respondents released = {$releasedCount}",
1114 * Get options for a given field.
1115 * @see CRM_Core_DAO::buildOptions
1117 * @param String $fieldName
1118 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
1119 * @param Array $props: whatever is known about this dao object
1121 * @return array|bool
1123 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1125 // Special logic for fields whose options depend on context or properties
1126 switch ($fieldName) {
1127 case 'activity_type_id':
1128 $campaignCompId = CRM_Core_Component
::getComponentID('CiviCampaign');
1129 if ($campaignCompId) {
1130 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1134 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);