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
37 * This class provides the functionality to record voter's interview.
39 class CRM_Campaign_Form_Task_Interview
extends CRM_Campaign_Form_Task
{
42 * The title of the group
49 * Variable to store redirect path
52 private $_userContext;
56 private $_surveyFields;
58 private $_surveyTypeId;
60 private $_interviewerId;
62 private $_surveyActivityIds;
64 private $_votingTab = FALSE;
66 private $_surveyValues;
68 private $_resultOptions;
70 private $_allowAjaxReleaseButton;
73 * Build all the data structures needed to build the form
77 public function preProcess() {
78 $this->_votingTab
= $this->get('votingTab');
79 $this->_reserveToInterview
= $this->get('reserveToInterview');
80 if ($this->_reserveToInterview ||
$this->_votingTab
) {
81 //user came from voting tab / reserve form.
83 'surveyId', 'contactIds', 'interviewerId') as $fld) {
84 $this->{"_$fld"} = $this->get($fld);
86 //get the target voter ids.
87 if ($this->_votingTab
) {
93 //get the survey id from user submitted values.
94 $this->_surveyId
= CRM_Utils_Array
::value('campaign_survey_id', $this->get('formValues'));
95 $this->_interviewerId
= CRM_Utils_Array
::value('survey_interviewer_id', $this->get('formValues'));
98 if ($this->_surveyId
) {
99 $params = array('id' => $this->_surveyId
);
100 CRM_Campaign_BAO_Survey
::retrieve($params, $this->_surveyDetails
);
103 $orderClause = FALSE;
104 $buttonName = $this->controller
->getButtonName();
105 if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
106 $orderByParams = CRM_Utils_Array
::value('order_bys', $_POST);
108 elseif (CRM_Core_OptionGroup
::getValue('activity_type', 'WalkList') == $this->_surveyDetails
['activity_type_id']) {
112 'column' => 'civicrm_address.street_name',
116 'column' => 'civicrm_address.street_number%2',
120 'column' => 'civicrm_address.street_number',
124 'column' => 'contact_a.sort_name',
131 if (!empty($orderByParams)) {
132 foreach ($orderByParams as $key => $val) {
133 if (!empty($val['column'])) {
134 $orderBy[] = "{$val['column']} {$val['order']}";
137 if (!empty($orderBy)) {
138 $orderClause = "ORDER BY " . implode(', ', $orderBy);
142 $this->_contactIds
= array_unique($this->_contactIds
);
143 if (!empty($this->_contactIds
) && $orderClause) {
144 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds
) . ' ) ';
147 FROM civicrm_contact contact_a
148 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
152 $this->_contactIds
= array();
153 $dao = CRM_Core_DAO
::executeQuery($sql);
154 while ($dao->fetch()) {
155 $this->_contactIds
[] = $dao->id
;
159 //get the contact read only fields to display.
160 $readOnlyFields = array_merge(array(
161 'contact_type' => '',
162 'sort_name' => ts('Name'),
165 //get the read only field data.
166 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
167 $returnProperties['contact_sub_type'] = TRUE;
169 //validate all voters for required activity.
170 //get the survey activities for given voters.
171 $this->_surveyActivityIds
= CRM_Campaign_BAO_Survey
::voterActivityDetails($this->_surveyId
,
173 $this->_interviewerId
175 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
176 $scheduledStatusId = array_search('Scheduled', $activityStatus);
178 $activityIds = array();
179 foreach ($this->_contactIds
as $key => $voterId) {
180 $actVals = CRM_Utils_Array
::value($voterId, $this->_surveyActivityIds
);
181 $statusId = CRM_Utils_Array
::value('status_id', $actVals);
182 $activityId = CRM_Utils_Array
::value('activity_id', $actVals);
185 $scheduledStatusId == $statusId
187 $activityIds["activity_id_{$voterId}"] = $activityId;
190 unset($this->_contactIds
[$key]);
194 //retrieve the contact details.
195 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
197 $this->_allowAjaxReleaseButton
= FALSE;
198 if ($this->_votingTab
&&
199 (CRM_Core_Permission
::check('manage campaign') ||
200 CRM_Core_Permission
::check('administer CiviCampaign') ||
201 CRM_Core_Permission
::check('release campaign contacts')
204 $this->_allowAjaxReleaseButton
= TRUE;
207 //validate voter ids across profile.
208 $this->filterVoterIds();
209 $this->assign('votingTab', $this->_votingTab
);
210 $this->assign('componentIds', $this->_contactIds
);
211 $this->assign('componentIdsJson', json_encode($this->_contactIds
));
212 $this->assign('voterDetails', $voterDetails);
213 $this->assign('readOnlyFields', $readOnlyFields);
214 $this->assign('interviewerId', $this->_interviewerId
);
215 $this->assign('surveyActivityIds', json_encode($activityIds));
216 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton
);
218 //get the survey values.
219 $this->_surveyValues
= $this->get('surveyValues');
220 if (!is_array($this->_surveyValues
)) {
221 $this->_surveyValues
= array();
222 if ($this->_surveyId
) {
223 $surveyParams = array('id' => $this->_surveyId
);
224 CRM_Campaign_BAO_Survey
::retrieve($surveyParams, $this->_surveyValues
);
226 $this->set('surveyValues', $this->_surveyValues
);
228 $this->assign('surveyValues', $this->_surveyValues
);
230 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
231 $this->assign("instanceId", $result);
233 //get the survey result options.
234 $this->_resultOptions
= $this->get('resultOptions');
235 if (!is_array($this->_resultOptions
)) {
236 $this->_resultOptions
= array();
237 if ($resultOptionId = CRM_Utils_Array
::value('result_id', $this->_surveyValues
)) {
238 $this->_resultOptions
= CRM_Core_OptionGroup
::valuesByID($resultOptionId);
240 $this->set('resultOptions', $this->_resultOptions
);
243 //validate the required ids.
244 $this->validateIds();
246 //append breadcrumb to survey dashboard.
247 if (CRM_Campaign_BAO_Campaign
::accessCampaign()) {
248 $url = CRM_Utils_System
::url('civicrm/campaign', 'reset=1&subPage=survey');
249 CRM_Utils_System
::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
253 $activityTypes = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
254 $this->_surveyTypeId
= CRM_Utils_Array
::value('activity_type_id', $this->_surveyValues
);
255 CRM_Utils_System
::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId
])));
258 public function validateIds() {
260 'surveyId' => ts('Could not find Survey.'),
261 'interviewerId' => ts('Could not find Interviewer.'),
262 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
263 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
266 $errorMessages = array();
267 foreach ($required as $fld => $msg) {
268 if (empty($this->{"_$fld"})) {
269 if (!$this->_votingTab
) {
270 CRM_Core_Error
::statusBounce($msg);
273 $errorMessages[] = $msg;
277 $this->assign('errorMessages', empty($errorMessages) ?
FALSE : $errorMessages);
281 * Build the form object
286 public function buildQuickForm() {
287 $this->assign('surveyTypeId', $this->_surveyTypeId
);
292 'civicrm_address.street_name' => 'Street Name',
293 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
294 'civicrm_address.street_number' => 'Street Number',
295 'contact_a.sort_name' => 'Respondent Name',
297 for ($i = 1; $i < count($options); $i++
) {
298 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
299 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
302 //pickup the uf fields.
303 $this->_surveyFields
= CRM_Campaign_BAO_Survey
::getSurveyResponseFields($this->_surveyId
,
307 foreach ($this->_contactIds
as $contactId) {
308 //build the profile fields.
309 foreach ($this->_surveyFields
as $name => $field) {
311 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, $contactId);
315 //build the result field.
316 if (!empty($this->_resultOptions
)) {
317 $this->add('select', "field[$contactId][result]", ts('Result'),
319 '' => ts('- select -')) +
320 array_combine($this->_resultOptions
, $this->_resultOptions
)
324 $this->add('text', "field[{$contactId}][note]", ts('Note'));
326 //need to keep control for release/reserve.
327 if ($this->_allowAjaxReleaseButton
) {
328 $this->addElement('hidden',
329 "field[{$contactId}][is_release_or_reserve]", 0,
330 array('id' => "field_{$contactId}_is_release_or_reserve")
334 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
336 //no need to get qf buttons.
337 if ($this->_votingTab
) {
344 'name' => ts('Done'),
345 'subName' => 'interview',
351 'name' => ts('Order By >>'),
352 'subName' => 'orderBy',
355 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
356 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
357 if ($manageCampaign ||
359 CRM_Core_Permission
::check('release campaign contacts')
363 'name' => ts('Release Respondents >>'),
364 'subName' => 'interviewToRelease',
367 if ($manageCampaign ||
369 CRM_Core_Permission
::check('reserve campaign contacts')
373 'name' => ts('Reserve More Respondents >>'),
374 'subName' => 'interviewToReserve',
378 $this->addButtons($buttons);
382 * Set default values for the form.
387 public function setDefaultValues() {
388 //load default data for only contact fields.
389 $contactFields = $defaults = array();
390 foreach ($this->_surveyFields
as $name => $field) {
391 $acceptable_types = CRM_Contact_BAO_ContactType
::basicTypes();
392 $acceptable_types[] = 'Contact';
393 if (in_array($field['field_type'], $acceptable_types)) {
394 $contactFields[$name] = $field;
397 if (!empty($contactFields)) {
398 foreach ($this->_contactIds
as $contactId) {
399 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
403 if (CRM_Core_OptionGroup
::getValue('activity_type', 'WalkList') == $this->_surveyDetails
['activity_type_id']) {
404 $defaults['order_bys'] =
407 'column' => 'civicrm_address.street_name',
411 'column' => 'civicrm_address.street_number%2',
415 'column' => 'civicrm_address.street_number',
419 'column' => 'contact_a.sort_name',
425 $defaults['order_bys'] =
429 'column' => 'contact_a.sort_name',
438 * Process the form after the input has been submitted and validated
443 public function postProcess() {
444 $buttonName = $this->controller
->getButtonName();
445 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
446 //hey its time to stop cycle.
447 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/survey/search', 'reset=1&op=reserve'));
449 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
450 //get ready to jump to release form.
452 'surveyId', 'contactIds', 'interviewerId') as $fld) {
453 $this->controller
->set($fld, $this->{"_$fld"});
455 $this->controller
->set('interviewToRelease', TRUE);
458 // vote is done through ajax
463 * @param array $params
467 public static function registerInterview($params) {
468 $activityId = CRM_Utils_Array
::value('activity_id', $params);
469 $surveyTypeId = CRM_Utils_Array
::value('activity_type_id', $params);
470 if (!is_array($params) ||
!$surveyTypeId ||
!$activityId) {
474 static $surveyFields;
475 if (!is_array($surveyFields)) {
476 $surveyFields = CRM_Core_BAO_CustomField
::getFields('Activity',
488 $statusId = array_search('Completed', CRM_Core_PseudoConstant
::activityStatus('name'));
491 //format custom fields.
492 $customParams = CRM_Core_BAO_CustomField
::postProcess($params,
498 CRM_Core_BAO_CustomValueTable
::store($customParams, 'civicrm_activity', $activityId);
500 //process contact data.
501 $contactParams = $fields = array();
503 $contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
504 $responseFields = CRM_Campaign_BAO_Survey
::getSurveyResponseFields($params['survey_id']);
505 if (!empty($responseFields)) {
506 foreach ($params as $key => $value) {
507 if (array_key_exists($key, $responseFields)) {
508 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
509 $fields[$key] = $responseFields[$key];
510 $contactParams[$key] = $value;
511 if (isset($params["{$key}_id"])) {
512 $contactParams["{$key}_id"] = $params["{$key}_id"];
519 $contactId = CRM_Utils_Array
::value('voter_id', $params);
520 if ($contactId && !empty($contactParams)) {
521 CRM_Contact_BAO_Contact
::createProfileContact($contactParams, $fields, $contactId);
524 //update activity record.
525 $activity = new CRM_Activity_DAO_Activity();
526 $activity->id
= $activityId;
528 $activity->selectAdd();
529 $activity->selectAdd('activity_date_time, status_id, result, subject');
530 $activity->find(TRUE);
531 $activity->activity_date_time
= date('YmdHis');
532 $activity->status_id
= $statusId;
534 if (!empty($params['activity_date_time'])) {
535 $activity->activity_date_time
= CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
539 $surveyTitle = CRM_Utils_Array
::value('surveyTitle', $params);
541 $subject = ts('%1', array(1 => $surveyTitle));
544 $subject .= ts('Respondent Interview');
546 $activity->subject
= $subject;
547 $activityParams = array(
548 'details' => 'details',
549 'result' => 'result',
550 'engagement_level' => 'activity_engagement_level',
551 'subject' => 'activity_subject',
552 'status_id' => 'activity_status_id',
553 'source_contact_id' => 'source_contact',
554 'location' => 'activity_location',
555 'campaign_id' => 'activity_campaign_id',
556 'duration' => 'activity_duration'
558 foreach ($activityParams as $key => $field) {
559 if (!empty($params[$field])) {
560 $activity->$key = $params[$field];
565 //really this should use Activity BAO& not be here but refactoring will have to be later
566 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
567 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
573 public function getVoterIds() {
574 if (!$this->_interviewerId
) {
575 $session = CRM_Core_Session
::singleton();
576 $this->_interviewerId
= $session->get('userID');
578 if (!$this->_surveyId
) {
579 // use default survey id
580 $dao = new CRM_Campaign_DAO_Survey();
582 $dao->is_default
= 1;
584 $this->_surveyId
= $dao->id
;
587 $this->_contactIds
= $this->get('contactIds');
588 if (!is_array($this->_contactIds
)) {
589 //get the survey activities.
590 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
591 $statusIds = array();
592 if ($statusId = array_search('Scheduled', $activityStatus)) {
593 $statusIds[] = $statusId;
595 $surveyActivities = CRM_Campaign_BAO_Survey
::getSurveyVoterInfo($this->_surveyId
,
596 $this->_interviewerId
,
599 $this->_contactIds
= array();
600 foreach ($surveyActivities as $val) {
601 $this->_contactIds
[$val['voter_id']] = $val['voter_id'];
603 $this->set('contactIds', $this->_contactIds
);
607 public function filterVoterIds() {
608 //do the cleanup later on.
609 if (!is_array($this->_contactIds
)) {
613 $profileId = CRM_Campaign_BAO_Survey
::getSurveyProfileId($this->_surveyId
);
615 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
616 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
617 $voterIdCount = count($this->_contactIds
);
619 //create temporary table to store voter ids.
620 $tempTableName = CRM_Core_DAO
::createTempTableName('civicrm_survey_respondent');
621 CRM_Core_DAO
::executeQuery("DROP TABLE IF EXISTS {$tempTableName}");
623 CREATE TEMPORARY TABLE {$tempTableName} (
624 id int unsigned NOT NULL AUTO_INCREMENT,
625 survey_contact_id int unsigned NOT NULL,
629 CRM_Core_DAO
::executeQuery($query);
633 $processIds = $this->_contactIds
;
634 $insertIds = array_splice($processIds, $insertedCount, $batch);
635 if (!empty($insertIds)) {
636 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
637 VALUES (" . implode('),(', $insertIds) . ');';
638 CRM_Core_DAO
::executeQuery($insertSQL);
640 $insertedCount +
= $batch;
641 } while ($insertedCount < $voterIdCount);
644 SELECT contact.id as id
645 FROM civicrm_contact contact
646 INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
647 WHERE contact.contact_type != %1";
648 $removeContact = CRM_Core_DAO
::executeQuery($query,
649 array(1 => array($profileType, 'String'))
651 while ($removeContact->fetch()) {
652 unset($this->_contactIds
[$removeContact->id
]);