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
;
160 //get the contact read only fields to display.
161 $readOnlyFields = array_merge(array(
162 'contact_type' => '',
163 'sort_name' => ts('Name'),
166 //get the read only field data.
167 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
168 $returnProperties['contact_sub_type'] = TRUE;
170 //validate all voters for required activity.
171 //get the survey activities for given voters.
172 $this->_surveyActivityIds
= CRM_Campaign_BAO_Survey
::voterActivityDetails($this->_surveyId
,
174 $this->_interviewerId
176 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
177 $scheduledStatusId = array_search('Scheduled', $activityStatus);
179 $activityIds = array();
180 foreach ($this->_contactIds
as $key => $voterId) {
181 $actVals = CRM_Utils_Array
::value($voterId, $this->_surveyActivityIds
);
182 $statusId = CRM_Utils_Array
::value('status_id', $actVals);
183 $activityId = CRM_Utils_Array
::value('activity_id', $actVals);
186 $scheduledStatusId == $statusId
188 $activityIds["activity_id_{$voterId}"] = $activityId;
191 unset($this->_contactIds
[$key]);
195 //retrieve the contact details.
196 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
198 $this->_allowAjaxReleaseButton
= FALSE;
199 if ($this->_votingTab
&&
200 (CRM_Core_Permission
::check('manage campaign') ||
201 CRM_Core_Permission
::check('administer CiviCampaign') ||
202 CRM_Core_Permission
::check('release campaign contacts')
205 $this->_allowAjaxReleaseButton
= TRUE;
208 //validate voter ids across profile.
209 $this->filterVoterIds();
210 $this->assign('votingTab', $this->_votingTab
);
211 $this->assign('componentIds', $this->_contactIds
);
212 $this->assign('componentIdsJson', json_encode($this->_contactIds
));
213 $this->assign('voterDetails', $voterDetails);
214 $this->assign('readOnlyFields', $readOnlyFields);
215 $this->assign('interviewerId', $this->_interviewerId
);
216 $this->assign('surveyActivityIds', json_encode($activityIds));
217 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton
);
219 //get the survey values.
220 $this->_surveyValues
= $this->get('surveyValues');
221 if (!is_array($this->_surveyValues
)) {
222 $this->_surveyValues
= array();
223 if ($this->_surveyId
) {
224 $surveyParams = array('id' => $this->_surveyId
);
225 CRM_Campaign_BAO_Survey
::retrieve($surveyParams, $this->_surveyValues
);
227 $this->set('surveyValues', $this->_surveyValues
);
229 $this->assign('surveyValues', $this->_surveyValues
);
231 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
232 $this->assign("instanceId",$result);
234 //get the survey result options.
235 $this->_resultOptions
= $this->get('resultOptions');
236 if (!is_array($this->_resultOptions
)) {
237 $this->_resultOptions
= array();
238 if ($resultOptionId = CRM_Utils_Array
::value('result_id', $this->_surveyValues
)) {
239 $this->_resultOptions
= CRM_Core_OptionGroup
::valuesByID($resultOptionId);
241 $this->set('resultOptions', $this->_resultOptions
);
244 //validate the required ids.
245 $this->validateIds();
247 //append breadcrumb to survey dashboard.
248 if (CRM_Campaign_BAO_Campaign
::accessCampaign()) {
249 $url = CRM_Utils_System
::url('civicrm/campaign', 'reset=1&subPage=survey');
250 CRM_Utils_System
::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
254 $activityTypes = CRM_Core_PseudoConstant
::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
255 $this->_surveyTypeId
= CRM_Utils_Array
::value('activity_type_id', $this->_surveyValues
);
256 CRM_Utils_System
::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId
])));
259 public function validateIds() {
260 $required = array('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
);
290 array('' => ' - none - ',
291 'civicrm_address.street_name' => 'Street Name',
292 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
293 'civicrm_address.street_number' => 'Street Number',
294 'contact_a.sort_name' => 'Respondent Name',
296 for ($i = 1; $i < count($options); $i++
) {
297 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
298 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
301 //pickup the uf fields.
302 $this->_surveyFields
= CRM_Campaign_BAO_Survey
::getSurveyResponseFields($this->_surveyId
,
306 foreach ($this->_contactIds
as $contactId) {
307 //build the profile fields.
308 foreach ($this->_surveyFields
as $name => $field) {
310 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, $contactId);
314 //build the result field.
315 if (!empty($this->_resultOptions
)) {
316 $this->add('select', "field[$contactId][result]", ts('Result'),
318 '' => ts('- select -')) +
319 array_combine($this->_resultOptions
, $this->_resultOptions
)
323 $this->add('text', "field[{$contactId}][note]", ts('Note'));
325 //need to keep control for release/reserve.
326 if ($this->_allowAjaxReleaseButton
) {
327 $this->addElement('hidden',
328 "field[{$contactId}][is_release_or_reserve]", 0,
329 array('id' => "field_{$contactId}_is_release_or_reserve")
333 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
335 //no need to get qf buttons.
336 if ($this->_votingTab
) {
341 array('type' => 'cancel',
342 'name' => ts('Done'),
343 'subName' => 'interview',
349 'name' => ts('Order By >>'),
350 'subName' => 'orderBy',
353 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
354 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
355 if ($manageCampaign ||
357 CRM_Core_Permission
::check('release campaign contacts')
361 'name' => ts('Release Respondents >>'),
362 'subName' => 'interviewToRelease',
365 if ($manageCampaign ||
367 CRM_Core_Permission
::check('reserve campaign contacts')
371 'name' => ts('Reserve More Respondents >>'),
372 'subName' => 'interviewToReserve',
376 $this->addButtons($buttons);
380 * Set default values for the form.
385 public function setDefaultValues() {
386 //load default data for only contact fields.
387 $contactFields = $defaults = array();
388 foreach ($this->_surveyFields
as $name => $field) {
389 $acceptable_types = CRM_Contact_BAO_ContactType
::basicTypes();
390 $acceptable_types[] = 'Contact';
391 if (in_array($field['field_type'], $acceptable_types)) {
392 $contactFields[$name] = $field;
395 if (!empty($contactFields)) {
396 foreach ($this->_contactIds
as $contactId) {
397 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
401 if ( CRM_Core_OptionGroup
::getValue('activity_type','WalkList') == $this->_surveyDetails
['activity_type_id'] ) {
402 $defaults['order_bys'] =
405 'column' => 'civicrm_address.street_name',
409 'column' => 'civicrm_address.street_number%2',
413 'column' => 'civicrm_address.street_number',
417 'column' => 'contact_a.sort_name',
423 $defaults['order_bys'] =
427 'column' => 'contact_a.sort_name',
436 * Process the form after the input has been submitted and validated
441 public function postProcess() {
442 $buttonName = $this->controller
->getButtonName();
443 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
444 //hey its time to stop cycle.
445 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/survey/search', 'reset=1&op=reserve'));
447 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
448 //get ready to jump to release form.
450 'surveyId', 'contactIds', 'interviewerId') as $fld) {
451 $this->controller
->set($fld, $this->{"_$fld"});
453 $this->controller
->set('interviewToRelease', TRUE);
456 // vote is done through ajax
461 * @param array $params
465 public static function registerInterview($params) {
466 $activityId = CRM_Utils_Array
::value('activity_id', $params);
467 $surveyTypeId = CRM_Utils_Array
::value('activity_type_id', $params);
468 if (!is_array($params) ||
!$surveyTypeId ||
!$activityId) {
472 static $surveyFields;
473 if (!is_array($surveyFields)) {
474 $surveyFields = CRM_Core_BAO_CustomField
::getFields('Activity',
486 $statusId = array_search('Completed', CRM_Core_PseudoConstant
::activityStatus('name'));
489 //format custom fields.
490 $customParams = CRM_Core_BAO_CustomField
::postProcess($params,
496 CRM_Core_BAO_CustomValueTable
::store($customParams, 'civicrm_activity', $activityId);
498 //process contact data.
499 $contactParams = $fields = array();
501 $contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
502 $responseFields = CRM_Campaign_BAO_Survey
::getSurveyResponseFields($params['survey_id']);
503 if (!empty($responseFields)) {
504 foreach ($params as $key => $value) {
505 if (array_key_exists($key, $responseFields)) {
506 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
507 $fields[$key] = $responseFields[$key];
508 $contactParams[$key] = $value;
509 if (isset($params["{$key}_id"])) {
510 $contactParams["{$key}_id"] = $params["{$key}_id"];
517 $contactId = CRM_Utils_Array
::value('voter_id', $params);
518 if ($contactId && !empty($contactParams)) {
519 CRM_Contact_BAO_Contact
::createProfileContact($contactParams, $fields, $contactId);
522 //update activity record.
523 $activity = new CRM_Activity_DAO_Activity();
524 $activity->id
= $activityId;
526 $activity->selectAdd();
527 $activity->selectAdd('activity_date_time, status_id, result, subject');
528 $activity->find(TRUE);
529 $activity->activity_date_time
= date('YmdHis');
530 $activity->status_id
= $statusId;
532 if (!empty($params['activity_date_time'])) {
533 $activity->activity_date_time
= CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
537 $surveyTitle = CRM_Utils_Array
::value('surveyTitle', $params);
539 $subject = ts('%1', array(1 => $surveyTitle));
542 $subject .= ts('Respondent Interview');
544 $activity->subject
= $subject;
545 $activityParams = array(
546 'details' => 'details',
547 'result' => 'result',
548 'engagement_level' => 'activity_engagement_level',
549 'subject' => 'activity_subject',
550 'status_id' => 'activity_status_id',
551 'source_contact_id' => 'source_contact',
552 'location' => 'activity_location',
553 'campaign_id' => 'activity_campaign_id',
554 'duration' => 'activity_duration'
556 foreach ($activityParams as $key => $field) {
557 if (!empty($params[$field])) {
558 $activity->$key = $params[$field];
563 //really this should use Activity BAO& not be here but refactoring will have to be later
564 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
565 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
571 public function getVoterIds() {
572 if (!$this->_interviewerId
) {
573 $session = CRM_Core_Session
::singleton();
574 $this->_interviewerId
= $session->get('userID');
576 if (!$this->_surveyId
) {
577 // use default survey id
578 $dao = new CRM_Campaign_DAO_Survey();
580 $dao->is_default
= 1;
582 $this->_surveyId
= $dao->id
;
585 $this->_contactIds
= $this->get('contactIds');
586 if (!is_array($this->_contactIds
)) {
587 //get the survey activities.
588 $activityStatus = CRM_Core_PseudoConstant
::activityStatus('name');
589 $statusIds = array();
590 if ($statusId = array_search('Scheduled', $activityStatus)) {
591 $statusIds[] = $statusId;
593 $surveyActivities = CRM_Campaign_BAO_Survey
::getSurveyVoterInfo($this->_surveyId
,
594 $this->_interviewerId
,
597 $this->_contactIds
= array();
598 foreach ($surveyActivities as $val) $this->_contactIds
[$val['voter_id']] = $val['voter_id'];
599 $this->set('contactIds', $this->_contactIds
);
603 public function filterVoterIds() {
604 //do the cleanup later on.
605 if (!is_array($this->_contactIds
)) {
609 $profileId = CRM_Campaign_BAO_Survey
::getSurveyProfileId($this->_surveyId
);
611 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
612 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
613 $voterIdCount = count($this->_contactIds
);
615 //create temporary table to store voter ids.
616 $tempTableName = CRM_Core_DAO
::createTempTableName('civicrm_survey_respondent');
617 CRM_Core_DAO
::executeQuery("DROP TABLE IF EXISTS {$tempTableName}");
619 CREATE TEMPORARY TABLE {$tempTableName} (
620 id int unsigned NOT NULL AUTO_INCREMENT,
621 survey_contact_id int unsigned NOT NULL,
625 CRM_Core_DAO
::executeQuery($query);
629 $processIds = $this->_contactIds
;
630 $insertIds = array_splice($processIds, $insertedCount, $batch);
631 if (!empty($insertIds)) {
632 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
633 VALUES (" . implode('),(', $insertIds) . ');';
634 CRM_Core_DAO
::executeQuery($insertSQL);
636 $insertedCount +
= $batch;
637 } while ($insertedCount < $voterIdCount);
640 SELECT contact.id as id
641 FROM civicrm_contact contact
642 INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
643 WHERE contact.contact_type != %1";
644 $removeContact = CRM_Core_DAO
::executeQuery($query,
645 array(1 => array($profileType, 'String'))
647 while ($removeContact->fetch()) {
648 unset($this->_contactIds
[$removeContact->id
]);