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
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
78 function preProcess() {
79 $this->_votingTab
= $this->get('votingTab');
80 $this->_reserveToInterview
= $this->get('reserveToInterview');
81 if ($this->_reserveToInterview ||
$this->_votingTab
) {
82 //user came from voting tab / reserve form.
84 'surveyId', 'contactIds', 'interviewerId') as $fld) {
85 $this->{"_$fld"} = $this->get($fld);
87 //get the target voter ids.
88 if ($this->_votingTab
) {
94 //get the survey id from user submitted values.
95 $this->_surveyId
= CRM_Utils_Array
::value('campaign_survey_id', $this->get('formValues'));
96 $this->_interviewerId
= CRM_Utils_Array
::value('survey_interviewer_id', $this->get('formValues'));
99 if ( $this->_surveyId
) {
100 $params = array('id' => $this->_surveyId
);
101 CRM_Campaign_BAO_Survey
::retrieve($params, $this->_surveyDetails
);
104 $orderClause = false;
105 $buttonName = $this->controller
->getButtonName();
106 if ( $buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
107 $orderByParams = CRM_Utils_Array
::value('order_bys', $_POST);
109 elseif ( CRM_Core_OptionGroup
::getValue('activity_type','WalkList') == $this->_surveyDetails
['activity_type_id'] ) {
114 'column' => 'civicrm_address.street_name',
119 'column' => 'civicrm_address.street_number%2',
124 'column' => 'civicrm_address.street_number',
129 'column' => 'contact_a.sort_name',
136 if ( !empty($orderByParams) ) {
137 foreach ( $orderByParams as $key => $val ) {
138 if (!empty($val['column'])) {
139 $orderBy[] = "{$val['column']} {$val['order']}";
142 if ( !empty($orderBy) ) {
143 $orderClause = "ORDER BY " . implode(', ', $orderBy);
147 $this->_contactIds
= array_unique($this->_contactIds
);
148 if (!empty($this->_contactIds
) && $orderClause) {
149 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds
) . ' ) ';
152 FROM civicrm_contact contact_a
153 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
157 $this->_contactIds
= array();
158 $dao = CRM_Core_DAO
::executeQuery($sql);
159 while ($dao->fetch()) {
160 $this->_contactIds
[] = $dao->id
;
165 //get the contact read only fields to display.
166 $readOnlyFields = array_merge(array(
167 'contact_type' => '',
168 'sort_name' => ts('Name'),
171 //get the read only field data.
172 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
173 $returnProperties['contact_sub_type'] = TRUE;
175 //validate all voters for required activity.
176 //get the survey activities for given voters.
177 $this->_surveyActivityIds
= CRM_Campaign_BAO_Survey
::voterActivityDetails($this->_surveyId
,
179 $this->_interviewerId
181 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
182 $scheduledStatusId = array_search('Scheduled', $activityStatus);
184 $activityIds = array();
185 foreach ($this->_contactIds
as $key => $voterId) {
186 $actVals = CRM_Utils_Array
::value($voterId, $this->_surveyActivityIds
);
187 $statusId = CRM_Utils_Array
::value('status_id', $actVals);
188 $activityId = CRM_Utils_Array
::value('activity_id', $actVals);
191 $scheduledStatusId == $statusId
193 $activityIds["activity_id_{$voterId}"] = $activityId;
196 unset($this->_contactIds
[$key]);
200 //retrieve the contact details.
201 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
203 $this->_allowAjaxReleaseButton
= FALSE;
204 if ($this->_votingTab
&&
205 (CRM_Core_Permission
::check('manage campaign') ||
206 CRM_Core_Permission
::check('administer CiviCampaign') ||
207 CRM_Core_Permission
::check('release campaign contacts')
210 $this->_allowAjaxReleaseButton
= TRUE;
213 //validate voter ids across profile.
214 $this->filterVoterIds();
215 $this->assign('votingTab', $this->_votingTab
);
216 $this->assign('componentIds', $this->_contactIds
);
217 $this->assign('componentIdsJson', json_encode($this->_contactIds
));
218 $this->assign('voterDetails', $voterDetails);
219 $this->assign('readOnlyFields', $readOnlyFields);
220 $this->assign('interviewerId', $this->_interviewerId
);
221 $this->assign('surveyActivityIds', json_encode($activityIds));
222 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton
);
224 //get the survey values.
225 $this->_surveyValues
= $this->get('surveyValues');
226 if (!is_array($this->_surveyValues
)) {
227 $this->_surveyValues
= array();
228 if ($this->_surveyId
) {
229 $surveyParams = array('id' => $this->_surveyId
);
230 CRM_Campaign_BAO_Survey
::retrieve($surveyParams, $this->_surveyValues
);
232 $this->set('surveyValues', $this->_surveyValues
);
234 $this->assign('surveyValues', $this->_surveyValues
);
236 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
237 $this->assign("instanceId",$result);
239 //get the survey result options.
240 $this->_resultOptions
= $this->get('resultOptions');
241 if (!is_array($this->_resultOptions
)) {
242 $this->_resultOptions
= array();
243 if ($resultOptionId = CRM_Utils_Array
::value('result_id', $this->_surveyValues
)) {
244 $this->_resultOptions
= CRM_Core_OptionGroup
::valuesByID($resultOptionId);
246 $this->set('resultOptions', $this->_resultOptions
);
249 //validate the required ids.
250 $this->validateIds();
252 //append breadcrumb to survey dashboard.
253 if (CRM_Campaign_BAO_Campaign
::accessCampaign()) {
254 $url = CRM_Utils_System
::url('civicrm/campaign', 'reset=1&subPage=survey');
255 CRM_Utils_System
::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
259 $activityTypes = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
260 $this->_surveyTypeId
= CRM_Utils_Array
::value('activity_type_id', $this->_surveyValues
);
261 CRM_Utils_System
::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId
])));
264 function validateIds() {
265 $required = array('surveyId' => ts('Could not find Survey.'),
266 'interviewerId' => ts('Could not find Interviewer.'),
267 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
268 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
271 $errorMessages = array();
272 foreach ($required as $fld => $msg) {
273 if (empty($this->{"_$fld"})) {
274 if (!$this->_votingTab
) {
275 CRM_Core_Error
::statusBounce($msg);
278 $errorMessages[] = $msg;
282 $this->assign('errorMessages', empty($errorMessages) ?
FALSE : $errorMessages);
292 function buildQuickForm() {
293 $this->assign('surveyTypeId', $this->_surveyTypeId
);
296 array('' => ' - none - ',
297 'civicrm_address.street_name' => 'Street Name',
298 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
299 'civicrm_address.street_number' => 'Street Number',
300 'contact_a.sort_name' => 'Respondent Name',
302 for ($i = 1; $i < count($options); $i++
) {
303 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
304 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', '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 -')) +
325 array_combine($this->_resultOptions
, $this->_resultOptions
)
329 $this->add('text', "field[{$contactId}][note]", ts('Note'));
331 //need to keep control for release/reserve.
332 if ($this->_allowAjaxReleaseButton
) {
333 $this->addElement('hidden',
334 "field[{$contactId}][is_release_or_reserve]", 0,
335 array('id' => "field_{$contactId}_is_release_or_reserve")
339 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
341 //no need to get qf buttons.
342 if ($this->_votingTab
) {
347 array('type' => 'cancel',
348 'name' => ts('Done'),
349 'subName' => 'interview',
355 'name' => ts('Order By >>'),
356 'subName' => 'orderBy',
359 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
360 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
361 if ($manageCampaign ||
363 CRM_Core_Permission
::check('release campaign contacts')
367 'name' => ts('Release Respondents >>'),
368 'subName' => 'interviewToRelease',
371 if ($manageCampaign ||
373 CRM_Core_Permission
::check('reserve campaign contacts')
377 'name' => ts('Reserve More Respondents >>'),
378 'subName' => 'interviewToReserve',
382 $this->addButtons($buttons);
386 * This function sets the default values for the form.
392 function setDefaultValues() {
393 //load default data for only contact fields.
394 $contactFields = $defaults = array();
395 foreach ($this->_surveyFields
as $name => $field) {
396 $acceptable_types = CRM_Contact_BAO_ContactType
::basicTypes();
397 $acceptable_types[] = 'Contact';
398 if (in_array($field['field_type'], $acceptable_types)) {
399 $contactFields[$name] = $field;
402 if (!empty($contactFields)) {
403 foreach ($this->_contactIds
as $contactId) {
404 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
408 if ( CRM_Core_OptionGroup
::getValue('activity_type','WalkList') == $this->_surveyDetails
['activity_type_id'] ) {
409 $defaults['order_bys'] =
413 'column' => 'civicrm_address.street_name',
418 'column' => 'civicrm_address.street_number%2',
423 'column' => 'civicrm_address.street_number',
428 'column' => 'contact_a.sort_name',
434 $defaults['order_bys'] =
438 'column' => 'contact_a.sort_name',
447 * process the form after the input has been submitted and validated
453 public function postProcess() {
454 $buttonName = $this->controller
->getButtonName();
455 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
456 //hey its time to stop cycle.
457 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/survey/search', 'reset=1&op=reserve'));
459 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
460 //get ready to jump to release form.
462 'surveyId', 'contactIds', 'interviewerId') as $fld) {
463 $this->controller
->set($fld, $this->{"_$fld"});
465 $this->controller
->set('interviewToRelease', TRUE);
468 // vote is done through ajax
477 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 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) $this->_contactIds
[$val['voter_id']] = $val['voter_id'];
611 $this->set('contactIds', $this->_contactIds
);
615 function filterVoterIds() {
616 //do the cleanup later on.
617 if (!is_array($this->_contactIds
)) {
621 $profileId = CRM_Campaign_BAO_Survey
::getSurveyProfileId($this->_surveyId
);
623 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
624 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
625 $voterIdCount = count($this->_contactIds
);
627 //create temporary table to store voter ids.
628 $tempTableName = CRM_Core_DAO
::createTempTableName('civicrm_survey_respondent');
629 CRM_Core_DAO
::executeQuery("DROP TABLE IF EXISTS {$tempTableName}");
631 CREATE TEMPORARY TABLE {$tempTableName} (
632 id int unsigned NOT NULL AUTO_INCREMENT,
633 survey_contact_id int unsigned NOT NULL,
637 CRM_Core_DAO
::executeQuery($query);
641 $processIds = $this->_contactIds
;
642 $insertIds = array_splice($processIds, $insertedCount, $batch);
643 if (!empty($insertIds)) {
644 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
645 VALUES (" . implode('),(', $insertIds) . ');';
646 CRM_Core_DAO
::executeQuery($insertSQL);
648 $insertedCount +
= $batch;
649 } while ($insertedCount < $voterIdCount);
652 SELECT contact.id as id
653 FROM civicrm_contact contact
654 INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
655 WHERE contact.contact_type != %1";
656 $removeContact = CRM_Core_DAO
::executeQuery($query,
657 array(1 => array($profileType, 'String'))
659 while ($removeContact->fetch()) {
660 unset($this->_contactIds
[$removeContact->id
]);