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
51 private $_userContext;
55 private $_surveyFields;
57 private $_surveyTypeId;
59 private $_interviewerId;
61 private $_surveyActivityIds;
63 private $_votingTab = FALSE;
65 private $_surveyValues;
67 private $_resultOptions;
69 private $_allowAjaxReleaseButton;
72 * Build all the data structures needed to build the form
76 public function preProcess() {
77 $this->_votingTab
= $this->get('votingTab');
78 $this->_reserveToInterview
= $this->get('reserveToInterview');
79 if ($this->_reserveToInterview ||
$this->_votingTab
) {
80 //user came from voting tab / reserve form.
86 $this->{"_$fld"} = $this->get($fld);
88 //get the target voter ids.
89 if ($this->_votingTab
) {
95 //get the survey id from user submitted values.
96 $this->_surveyId
= CRM_Utils_Array
::value('campaign_survey_id', $this->get('formValues'));
97 $this->_interviewerId
= CRM_Utils_Array
::value('survey_interviewer_id', $this->get('formValues'));
100 if ($this->_surveyId
) {
101 $params = array('id' => $this->_surveyId
);
102 CRM_Campaign_BAO_Survey
::retrieve($params, $this->_surveyDetails
);
105 $orderClause = FALSE;
106 $buttonName = $this->controller
->getButtonName();
107 if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
108 $orderByParams = CRM_Utils_Array
::value('order_bys', $_POST);
110 elseif (CRM_Core_OptionGroup
::getValue('activity_type', 'WalkList') == $this->_surveyDetails
['activity_type_id']) {
114 'column' => 'civicrm_address.street_name',
118 'column' => 'civicrm_address.street_number%2',
122 'column' => 'civicrm_address.street_number',
126 'column' => 'contact_a.sort_name',
133 if (!empty($orderByParams)) {
134 foreach ($orderByParams as $key => $val) {
135 if (!empty($val['column'])) {
136 $orderBy[] = "{$val['column']} {$val['order']}";
139 if (!empty($orderBy)) {
140 $orderClause = "ORDER BY " . implode(', ', $orderBy);
144 $this->_contactIds
= array_unique($this->_contactIds
);
145 if (!empty($this->_contactIds
) && $orderClause) {
146 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds
) . ' ) ';
149 FROM civicrm_contact contact_a
150 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
154 $this->_contactIds
= array();
155 $dao = CRM_Core_DAO
::executeQuery($sql);
156 while ($dao->fetch()) {
157 $this->_contactIds
[] = $dao->id
;
161 //get the contact read only fields to display.
162 $readOnlyFields = array_merge(array(
163 'contact_type' => '',
164 'sort_name' => ts('Name'),
167 //get the read only field data.
168 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
169 $returnProperties['contact_sub_type'] = TRUE;
171 //validate all voters for required activity.
172 //get the survey activities for given voters.
173 $this->_surveyActivityIds
= CRM_Campaign_BAO_Survey
::voterActivityDetails($this->_surveyId
,
175 $this->_interviewerId
177 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
178 $scheduledStatusId = array_search('Scheduled', $activityStatus);
180 $activityIds = array();
181 foreach ($this->_contactIds
as $key => $voterId) {
182 $actVals = CRM_Utils_Array
::value($voterId, $this->_surveyActivityIds
);
183 $statusId = CRM_Utils_Array
::value('status_id', $actVals);
184 $activityId = CRM_Utils_Array
::value('activity_id', $actVals);
187 $scheduledStatusId == $statusId
189 $activityIds["activity_id_{$voterId}"] = $activityId;
192 unset($this->_contactIds
[$key]);
196 //retrieve the contact details.
197 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
199 $this->_allowAjaxReleaseButton
= FALSE;
200 if ($this->_votingTab
&&
201 (CRM_Core_Permission
::check('manage campaign') ||
202 CRM_Core_Permission
::check('administer CiviCampaign') ||
203 CRM_Core_Permission
::check('release campaign contacts')
206 $this->_allowAjaxReleaseButton
= TRUE;
209 //validate voter ids across profile.
210 $this->filterVoterIds();
211 $this->assign('votingTab', $this->_votingTab
);
212 $this->assign('componentIds', $this->_contactIds
);
213 $this->assign('componentIdsJson', json_encode($this->_contactIds
));
214 $this->assign('voterDetails', $voterDetails);
215 $this->assign('readOnlyFields', $readOnlyFields);
216 $this->assign('interviewerId', $this->_interviewerId
);
217 $this->assign('surveyActivityIds', json_encode($activityIds));
218 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton
);
220 //get the survey values.
221 $this->_surveyValues
= $this->get('surveyValues');
222 if (!is_array($this->_surveyValues
)) {
223 $this->_surveyValues
= array();
224 if ($this->_surveyId
) {
225 $surveyParams = array('id' => $this->_surveyId
);
226 CRM_Campaign_BAO_Survey
::retrieve($surveyParams, $this->_surveyValues
);
228 $this->set('surveyValues', $this->_surveyValues
);
230 $this->assign('surveyValues', $this->_surveyValues
);
232 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
233 $this->assign("instanceId", $result);
235 //get the survey result options.
236 $this->_resultOptions
= $this->get('resultOptions');
237 if (!is_array($this->_resultOptions
)) {
238 $this->_resultOptions
= array();
239 if ($resultOptionId = CRM_Utils_Array
::value('result_id', $this->_surveyValues
)) {
240 $this->_resultOptions
= CRM_Core_OptionGroup
::valuesByID($resultOptionId);
242 $this->set('resultOptions', $this->_resultOptions
);
245 //validate the required ids.
246 $this->validateIds();
248 //append breadcrumb to survey dashboard.
249 if (CRM_Campaign_BAO_Campaign
::accessCampaign()) {
250 $url = CRM_Utils_System
::url('civicrm/campaign', 'reset=1&subPage=survey');
251 CRM_Utils_System
::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
255 $activityTypes = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
256 $this->_surveyTypeId
= CRM_Utils_Array
::value('activity_type_id', $this->_surveyValues
);
257 CRM_Utils_System
::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId
])));
260 public function validateIds() {
262 'surveyId' => ts('Could not find Survey.'),
263 'interviewerId' => ts('Could not find Interviewer.'),
264 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
265 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
268 $errorMessages = array();
269 foreach ($required as $fld => $msg) {
270 if (empty($this->{"_$fld"})) {
271 if (!$this->_votingTab
) {
272 CRM_Core_Error
::statusBounce($msg);
275 $errorMessages[] = $msg;
279 $this->assign('errorMessages', empty($errorMessages) ?
FALSE : $errorMessages);
283 * Build the form object
288 public function buildQuickForm() {
289 $this->assign('surveyTypeId', $this->_surveyTypeId
);
294 'civicrm_address.street_name' => 'Street Name',
295 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
296 'civicrm_address.street_number' => 'Street Number',
297 'contact_a.sort_name' => 'Respondent Name',
299 for ($i = 1; $i < count($options); $i++
) {
300 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
301 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
302 'ASC' => 'Ascending',
303 'DESC' => 'Descending'
307 //pickup the uf fields.
308 $this->_surveyFields
= CRM_Campaign_BAO_Survey
::getSurveyResponseFields($this->_surveyId
,
312 foreach ($this->_contactIds
as $contactId) {
313 //build the profile fields.
314 foreach ($this->_surveyFields
as $name => $field) {
316 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, $contactId);
320 //build the result field.
321 if (!empty($this->_resultOptions
)) {
322 $this->add('select', "field[$contactId][result]", ts('Result'),
324 '' => ts('- select -')
326 array_combine($this->_resultOptions
, $this->_resultOptions
)
330 $this->add('text', "field[{$contactId}][note]", ts('Note'));
332 //need to keep control for release/reserve.
333 if ($this->_allowAjaxReleaseButton
) {
334 $this->addElement('hidden',
335 "field[{$contactId}][is_release_or_reserve]", 0,
336 array('id' => "field_{$contactId}_is_release_or_reserve")
340 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
342 //no need to get qf buttons.
343 if ($this->_votingTab
) {
350 'name' => ts('Done'),
351 'subName' => 'interview',
358 'name' => ts('Order By >>'),
359 'subName' => 'orderBy',
362 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
363 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
364 if ($manageCampaign ||
366 CRM_Core_Permission
::check('release campaign contacts')
370 'name' => ts('Release Respondents >>'),
371 'subName' => 'interviewToRelease',
374 if ($manageCampaign ||
376 CRM_Core_Permission
::check('reserve campaign contacts')
380 'name' => ts('Reserve More Respondents >>'),
381 'subName' => 'interviewToReserve',
385 $this->addButtons($buttons);
389 * Set default values for the form.
394 public function setDefaultValues() {
395 //load default data for only contact fields.
396 $contactFields = $defaults = array();
397 foreach ($this->_surveyFields
as $name => $field) {
398 $acceptable_types = CRM_Contact_BAO_ContactType
::basicTypes();
399 $acceptable_types[] = 'Contact';
400 if (in_array($field['field_type'], $acceptable_types)) {
401 $contactFields[$name] = $field;
404 if (!empty($contactFields)) {
405 foreach ($this->_contactIds
as $contactId) {
406 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
410 if (CRM_Core_OptionGroup
::getValue('activity_type', 'WalkList') == $this->_surveyDetails
['activity_type_id']) {
411 $defaults['order_bys'] =
414 'column' => 'civicrm_address.street_name',
418 'column' => 'civicrm_address.street_number%2',
422 'column' => 'civicrm_address.street_number',
426 'column' => 'contact_a.sort_name',
432 $defaults['order_bys'] =
436 'column' => 'contact_a.sort_name',
445 * Process the form after the input has been submitted and validated
450 public function postProcess() {
451 $buttonName = $this->controller
->getButtonName();
452 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
453 //hey its time to stop cycle.
454 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/survey/search', 'reset=1&op=reserve'));
456 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
457 //get ready to jump to release form.
463 $this->controller
->set($fld, $this->{"_$fld"});
465 $this->controller
->set('interviewToRelease', TRUE);
468 // vote is done through ajax
473 * @param array $params
477 public static function registerInterview($params) {
478 $activityId = CRM_Utils_Array
::value('activity_id', $params);
479 $surveyTypeId = CRM_Utils_Array
::value('activity_type_id', $params);
480 if (!is_array($params) ||
!$surveyTypeId ||
!$activityId) {
484 static $surveyFields;
485 if (!is_array($surveyFields)) {
486 $surveyFields = CRM_Core_BAO_CustomField
::getFields('Activity',
498 $statusId = array_search('Completed', CRM_Core_PseudoConstant
::activityStatus('name'));
501 //format custom fields.
502 $customParams = CRM_Core_BAO_CustomField
::postProcess($params,
508 CRM_Core_BAO_CustomValueTable
::store($customParams, 'civicrm_activity', $activityId);
510 //process contact data.
511 $contactParams = $fields = array();
513 $contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
514 $responseFields = CRM_Campaign_BAO_Survey
::getSurveyResponseFields($params['survey_id']);
515 if (!empty($responseFields)) {
516 foreach ($params as $key => $value) {
517 if (array_key_exists($key, $responseFields)) {
518 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
519 $fields[$key] = $responseFields[$key];
520 $contactParams[$key] = $value;
521 if (isset($params["{$key}_id"])) {
522 $contactParams["{$key}_id"] = $params["{$key}_id"];
529 $contactId = CRM_Utils_Array
::value('voter_id', $params);
530 if ($contactId && !empty($contactParams)) {
531 CRM_Contact_BAO_Contact
::createProfileContact($contactParams, $fields, $contactId);
534 //update activity record.
535 $activity = new CRM_Activity_DAO_Activity();
536 $activity->id
= $activityId;
538 $activity->selectAdd();
539 $activity->selectAdd('activity_date_time, status_id, result, subject');
540 $activity->find(TRUE);
541 $activity->activity_date_time
= date('YmdHis');
542 $activity->status_id
= $statusId;
544 if (!empty($params['activity_date_time'])) {
545 $activity->activity_date_time
= CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
549 $surveyTitle = CRM_Utils_Array
::value('surveyTitle', $params);
551 $subject = ts('%1', array(1 => $surveyTitle));
554 $subject .= ts('Respondent Interview');
556 $activity->subject
= $subject;
557 $activityParams = array(
558 'details' => 'details',
559 'result' => 'result',
560 'engagement_level' => 'activity_engagement_level',
561 'subject' => 'activity_subject',
562 'status_id' => 'activity_status_id',
563 'source_contact_id' => 'source_contact',
564 'location' => 'activity_location',
565 'campaign_id' => 'activity_campaign_id',
566 'duration' => 'activity_duration',
568 foreach ($activityParams as $key => $field) {
569 if (!empty($params[$field])) {
570 $activity->$key = $params[$field];
575 //really this should use Activity BAO& not be here but refactoring will have to be later
576 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
577 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
583 public function getVoterIds() {
584 if (!$this->_interviewerId
) {
585 $session = CRM_Core_Session
::singleton();
586 $this->_interviewerId
= $session->get('userID');
588 if (!$this->_surveyId
) {
589 // use default survey id
590 $dao = new CRM_Campaign_DAO_Survey();
592 $dao->is_default
= 1;
594 $this->_surveyId
= $dao->id
;
597 $this->_contactIds
= $this->get('contactIds');
598 if (!is_array($this->_contactIds
)) {
599 //get the survey activities.
600 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
601 $statusIds = array();
602 if ($statusId = array_search('Scheduled', $activityStatus)) {
603 $statusIds[] = $statusId;
605 $surveyActivities = CRM_Campaign_BAO_Survey
::getSurveyVoterInfo($this->_surveyId
,
606 $this->_interviewerId
,
609 $this->_contactIds
= array();
610 foreach ($surveyActivities as $val) {
611 $this->_contactIds
[$val['voter_id']] = $val['voter_id'];
613 $this->set('contactIds', $this->_contactIds
);
617 public function filterVoterIds() {
618 //do the cleanup later on.
619 if (!is_array($this->_contactIds
)) {
623 $profileId = CRM_Campaign_BAO_Survey
::getSurveyProfileId($this->_surveyId
);
625 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
626 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
627 $voterIdCount = count($this->_contactIds
);
629 //create temporary table to store voter ids.
630 $tempTableName = CRM_Core_DAO
::createTempTableName('civicrm_survey_respondent');
631 CRM_Core_DAO
::executeQuery("DROP TABLE IF EXISTS {$tempTableName}");
633 CREATE TEMPORARY TABLE {$tempTableName} (
634 id int unsigned NOT NULL AUTO_INCREMENT,
635 survey_contact_id int unsigned NOT NULL,
639 CRM_Core_DAO
::executeQuery($query);
643 $processIds = $this->_contactIds
;
644 $insertIds = array_splice($processIds, $insertedCount, $batch);
645 if (!empty($insertIds)) {
646 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
647 VALUES (" . implode('),(', $insertIds) . ');';
648 CRM_Core_DAO
::executeQuery($insertSQL);
650 $insertedCount +
= $batch;
651 } while ($insertedCount < $voterIdCount);
654 SELECT contact.id as id
655 FROM civicrm_contact contact
656 INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
657 WHERE contact.contact_type != %1";
658 $removeContact = CRM_Core_DAO
::executeQuery($query,
659 array(1 => array($profileType, 'String'))
661 while ($removeContact->fetch()) {
662 unset($this->_contactIds
[$removeContact->id
]);