Merge pull request #14878 from civicrm/5.16
[civicrm-core.git] / CRM / Campaign / Form / Task / Interview.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
35 * This class provides the functionality to record voter's interview.
36 */
37class CRM_Campaign_Form_Task_Interview extends CRM_Campaign_Form_Task {
38
39 /**
100fef9d 40 * The title of the group
6a488035
TO
41 *
42 * @var string
43 */
44 protected $_title;
45
46 /**
100fef9d 47 * Variable to store redirect path
f157740d 48 * @var string
6a488035
TO
49 */
50 private $_userContext;
51
52 private $_groupTree;
53
54 private $_surveyFields;
55
56 private $_surveyTypeId;
57
58 private $_interviewerId;
59
60 private $_surveyActivityIds;
61
62 private $_votingTab = FALSE;
63
64 private $_surveyValues;
65
66 private $_resultOptions;
67
68 private $_allowAjaxReleaseButton;
69
70 /**
fe482240 71 * Build all the data structures needed to build the form.
6a488035 72 */
00be9182 73 public function preProcess() {
6a488035
TO
74 $this->_votingTab = $this->get('votingTab');
75 $this->_reserveToInterview = $this->get('reserveToInterview');
76 if ($this->_reserveToInterview || $this->_votingTab) {
77 //user came from voting tab / reserve form.
be2fb01f 78 foreach ([
5d4fcf54
TO
79 'surveyId',
80 'contactIds',
81 'interviewerId',
82 ] as $fld) {
6a488035
TO
83 $this->{"_$fld"} = $this->get($fld);
84 }
85 //get the target voter ids.
86 if ($this->_votingTab) {
87 $this->getVoterIds();
88 }
89 }
90 else {
91 parent::preProcess();
92 //get the survey id from user submitted values.
93 $this->_surveyId = CRM_Utils_Array::value('campaign_survey_id', $this->get('formValues'));
94 $this->_interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->get('formValues'));
95 }
96
481a74f4 97 if ($this->_surveyId) {
be2fb01f 98 $params = ['id' => $this->_surveyId];
6a488035
TO
99 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
100 }
101
94880218 102 $orderClause = FALSE;
353ffa53 103 $buttonName = $this->controller->getButtonName();
c9e87d28 104 $walkListActivityId = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
481a74f4 105 if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
6a488035
TO
106 $orderByParams = CRM_Utils_Array::value('order_bys', $_POST);
107 }
c9e87d28 108 elseif ($walkListActivityId == $this->_surveyDetails['activity_type_id']) {
acb1052e 109 $orderByParams
be2fb01f
CW
110 = [
111 1 => [
6a488035 112 'column' => 'civicrm_address.street_name',
353ffa53 113 'order' => 'ASC',
be2fb01f
CW
114 ],
115 2 => [
6a488035
TO
116 'column' => 'civicrm_address.street_number%2',
117 'order' => 'ASC',
be2fb01f
CW
118 ],
119 3 => [
6a488035
TO
120 'column' => 'civicrm_address.street_number',
121 'order' => 'ASC',
be2fb01f
CW
122 ],
123 4 => [
6a488035
TO
124 'column' => 'contact_a.sort_name',
125 'order' => 'ASC',
be2fb01f
CW
126 ],
127 ];
6a488035
TO
128 }
129
be2fb01f 130 $orderBy = [];
481a74f4
TO
131 if (!empty($orderByParams)) {
132 foreach ($orderByParams as $key => $val) {
a7488080 133 if (!empty($val['column'])) {
6a488035
TO
134 $orderBy[] = "{$val['column']} {$val['order']}";
135 }
136 }
481a74f4 137 if (!empty($orderBy)) {
6a488035
TO
138 $orderClause = "ORDER BY " . implode(', ', $orderBy);
139 }
140 }
141
142 $this->_contactIds = array_unique($this->_contactIds);
143 if (!empty($this->_contactIds) && $orderClause) {
144 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds) . ' ) ';
353ffa53 145 $sql = "
6a488035
TO
146SELECT contact_a.id
147FROM civicrm_contact contact_a
148LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
149WHERE {$clause}
150{$orderClause}";
151
be2fb01f 152 $this->_contactIds = [];
6a488035
TO
153 $dao = CRM_Core_DAO::executeQuery($sql);
154 while ($dao->fetch()) {
155 $this->_contactIds[] = $dao->id;
156 }
157 }
158
6a488035 159 //get the contact read only fields to display.
be2fb01f 160 $readOnlyFields = array_merge([
6a488035
TO
161 'contact_type' => '',
162 'sort_name' => ts('Name'),
be2fb01f 163 ]);
6a488035
TO
164
165 //get the read only field data.
166 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
167 $returnProperties['contact_sub_type'] = TRUE;
168
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,
172 $this->_contactIds,
173 $this->_interviewerId
174 );
c9e87d28 175 $scheduledStatusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
6a488035 176
be2fb01f 177 $activityIds = [];
6a488035 178 foreach ($this->_contactIds as $key => $voterId) {
353ffa53
TO
179 $actVals = CRM_Utils_Array::value($voterId, $this->_surveyActivityIds);
180 $statusId = CRM_Utils_Array::value('status_id', $actVals);
6a488035
TO
181 $activityId = CRM_Utils_Array::value('activity_id', $actVals);
182 if ($activityId &&
183 $statusId &&
184 $scheduledStatusId == $statusId
185 ) {
186 $activityIds["activity_id_{$voterId}"] = $activityId;
187 }
188 else {
189 unset($this->_contactIds[$key]);
190 }
191 }
192
193 //retrieve the contact details.
194 $voterDetails = CRM_Campaign_BAO_Survey::voterDetails($this->_contactIds, $returnProperties);
195
196 $this->_allowAjaxReleaseButton = FALSE;
197 if ($this->_votingTab &&
198 (CRM_Core_Permission::check('manage campaign') ||
199 CRM_Core_Permission::check('administer CiviCampaign') ||
200 CRM_Core_Permission::check('release campaign contacts')
201 )
202 ) {
203 $this->_allowAjaxReleaseButton = TRUE;
204 }
205
206 //validate voter ids across profile.
207 $this->filterVoterIds();
208 $this->assign('votingTab', $this->_votingTab);
209 $this->assign('componentIds', $this->_contactIds);
210 $this->assign('componentIdsJson', json_encode($this->_contactIds));
211 $this->assign('voterDetails', $voterDetails);
212 $this->assign('readOnlyFields', $readOnlyFields);
213 $this->assign('interviewerId', $this->_interviewerId);
214 $this->assign('surveyActivityIds', json_encode($activityIds));
215 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton);
216
217 //get the survey values.
218 $this->_surveyValues = $this->get('surveyValues');
219 if (!is_array($this->_surveyValues)) {
be2fb01f 220 $this->_surveyValues = [];
6a488035 221 if ($this->_surveyId) {
be2fb01f 222 $surveyParams = ['id' => $this->_surveyId];
6a488035
TO
223 CRM_Campaign_BAO_Survey::retrieve($surveyParams, $this->_surveyValues);
224 }
225 $this->set('surveyValues', $this->_surveyValues);
226 }
227 $this->assign('surveyValues', $this->_surveyValues);
228
229 $result = CRM_Campaign_BAO_Survey::getReportID($this->_surveyId);
94880218 230 $this->assign("instanceId", $result);
6a488035
TO
231
232 //get the survey result options.
233 $this->_resultOptions = $this->get('resultOptions');
234 if (!is_array($this->_resultOptions)) {
be2fb01f 235 $this->_resultOptions = [];
6a488035
TO
236 if ($resultOptionId = CRM_Utils_Array::value('result_id', $this->_surveyValues)) {
237 $this->_resultOptions = CRM_Core_OptionGroup::valuesByID($resultOptionId);
238 }
239 $this->set('resultOptions', $this->_resultOptions);
240 }
241
242 //validate the required ids.
243 $this->validateIds();
244
245 //append breadcrumb to survey dashboard.
246 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
247 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
be2fb01f 248 CRM_Utils_System::appendBreadCrumb([['title' => ts('Survey(s)'), 'url' => $url]]);
6a488035
TO
249 }
250
251 //set the title.
6a488035 252 $this->_surveyTypeId = CRM_Utils_Array::value('activity_type_id', $this->_surveyValues);
c9e87d28 253 $surveyTypeLabel = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $this->_surveyTypeId);
be2fb01f 254 CRM_Utils_System::setTitle(ts('Record %1 Responses', [1 => $surveyTypeLabel]));
6a488035
TO
255 }
256
00be9182 257 public function validateIds() {
be2fb01f 258 $required = [
353ffa53 259 'surveyId' => ts('Could not find Survey.'),
6a488035
TO
260 'interviewerId' => ts('Could not find Interviewer.'),
261 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
262 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
be2fb01f 263 ];
6a488035 264
be2fb01f 265 $errorMessages = [];
6a488035
TO
266 foreach ($required as $fld => $msg) {
267 if (empty($this->{"_$fld"})) {
268 if (!$this->_votingTab) {
269 CRM_Core_Error::statusBounce($msg);
270 break;
271 }
272 $errorMessages[] = $msg;
273 }
274 }
275
276 $this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
277 }
278
279 /**
fe482240 280 * Build the form object.
6a488035 281 */
00be9182 282 public function buildQuickForm() {
6a488035
TO
283 $this->assign('surveyTypeId', $this->_surveyTypeId);
284
acb1052e 285 $options
be2fb01f 286 = [
353ffa53
TO
287 '' => ' - none - ',
288 'civicrm_address.street_name' => 'Street Name',
6a488035 289 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
353ffa53
TO
290 'civicrm_address.street_number' => 'Street Number',
291 'contact_a.sort_name' => 'Respondent Name',
be2fb01f 292 ];
6a488035
TO
293 for ($i = 1; $i < count($options); $i++) {
294 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
be2fb01f 295 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
5d4fcf54
TO
296 'ASC' => ts('Ascending'),
297 'DESC' => ts('Descending'),
298 ]);
6a488035
TO
299 }
300
301 //pickup the uf fields.
302 $this->_surveyFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($this->_surveyId,
303 $this->_surveyTypeId
304 );
305
306 foreach ($this->_contactIds as $contactId) {
307 //build the profile fields.
308 foreach ($this->_surveyFields as $name => $field) {
9b873358 309 if ($field) {
6a488035
TO
310 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId);
311 }
312 }
313
314 //build the result field.
315 if (!empty($this->_resultOptions)) {
316 $this->add('select', "field[$contactId][result]", ts('Result'),
be2fb01f 317 [
a130e045 318 '' => ts('- select -'),
be2fb01f 319 ] +
353ffa53 320 array_combine($this->_resultOptions, $this->_resultOptions)
6a488035
TO
321 );
322 }
323
324 $this->add('text', "field[{$contactId}][note]", ts('Note'));
325
326 //need to keep control for release/reserve.
327 if ($this->_allowAjaxReleaseButton) {
328 $this->addElement('hidden',
329 "field[{$contactId}][is_release_or_reserve]", 0,
be2fb01f 330 ['id' => "field_{$contactId}_is_release_or_reserve"]
6a488035
TO
331 );
332 }
333 }
334 $this->assign('surveyFields', empty($this->_surveyFields) ? FALSE : $this->_surveyFields);
335
336 //no need to get qf buttons.
337 if ($this->_votingTab) {
338 return;
339 }
340
be2fb01f
CW
341 $buttons = [
342 [
353ffa53 343 'type' => 'cancel',
6a488035
TO
344 'name' => ts('Done'),
345 'subName' => 'interview',
346 'isDefault' => TRUE,
be2fb01f
CW
347 ],
348 ];
6a488035 349
be2fb01f 350 $buttons[] = [
6a488035
TO
351 'type' => 'submit',
352 'name' => ts('Order By >>'),
353 'subName' => 'orderBy',
be2fb01f 354 ];
6a488035
TO
355
356 $manageCampaign = CRM_Core_Permission::check('manage campaign');
357 $adminCampaign = CRM_Core_Permission::check('administer CiviCampaign');
358 if ($manageCampaign ||
359 $adminCampaign ||
360 CRM_Core_Permission::check('release campaign contacts')
361 ) {
be2fb01f 362 $buttons[] = [
6a488035
TO
363 'type' => 'next',
364 'name' => ts('Release Respondents >>'),
365 'subName' => 'interviewToRelease',
be2fb01f 366 ];
6a488035
TO
367 }
368 if ($manageCampaign ||
369 $adminCampaign ||
370 CRM_Core_Permission::check('reserve campaign contacts')
371 ) {
be2fb01f 372 $buttons[] = [
6a488035
TO
373 'type' => 'done',
374 'name' => ts('Reserve More Respondents >>'),
375 'subName' => 'interviewToReserve',
be2fb01f 376 ];
6a488035
TO
377 }
378
379 $this->addButtons($buttons);
380 }
381
382 /**
c490a46a 383 * Set default values for the form.
6a488035 384 */
00be9182 385 public function setDefaultValues() {
6a488035 386 //load default data for only contact fields.
be2fb01f 387 $contactFields = $defaults = [];
6a488035
TO
388 foreach ($this->_surveyFields as $name => $field) {
389 $acceptable_types = CRM_Contact_BAO_ContactType::basicTypes();
390 $acceptable_types[] = 'Contact';
c9e87d28 391 if (isset($field['field_type']) && (in_array($field['field_type'], $acceptable_types))) {
6a488035
TO
392 $contactFields[$name] = $field;
393 }
394 }
395 if (!empty($contactFields)) {
396 foreach ($this->_contactIds as $contactId) {
397 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
398 }
399 }
400
c9e87d28
MW
401 $walkListActivityId = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
402 if ($walkListActivityId == $this->_surveyDetails['activity_type_id']) {
acb1052e 403 $defaults['order_bys']
be2fb01f
CW
404 = [
405 1 => [
6a488035 406 'column' => 'civicrm_address.street_name',
353ffa53 407 'order' => 'ASC',
be2fb01f
CW
408 ],
409 2 => [
6a488035
TO
410 'column' => 'civicrm_address.street_number%2',
411 'order' => 'ASC',
be2fb01f
CW
412 ],
413 3 => [
6a488035
TO
414 'column' => 'civicrm_address.street_number',
415 'order' => 'ASC',
be2fb01f
CW
416 ],
417 4 => [
6a488035
TO
418 'column' => 'contact_a.sort_name',
419 'order' => 'ASC',
be2fb01f
CW
420 ],
421 ];
6a488035
TO
422 }
423 else {
acb1052e 424 $defaults['order_bys']
be2fb01f
CW
425 = [
426 1 => [
a130e045
DG
427 'column' => 'contact_a.sort_name',
428 'order' => 'ASC',
be2fb01f
CW
429 ],
430 ];
6a488035
TO
431 }
432 return $defaults;
433 }
434
435 /**
fe482240 436 * Process the form after the input has been submitted and validated.
6a488035
TO
437 */
438 public function postProcess() {
439 $buttonName = $this->controller->getButtonName();
440 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
441 //hey its time to stop cycle.
442 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/survey/search', 'reset=1&op=reserve'));
443 }
444 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
445 //get ready to jump to release form.
be2fb01f 446 foreach ([
5d4fcf54
TO
447 'surveyId',
448 'contactIds',
449 'interviewerId',
450 ] as $fld) {
6a488035
TO
451 $this->controller->set($fld, $this->{"_$fld"});
452 }
453 $this->controller->set('interviewToRelease', TRUE);
454 }
455
456 // vote is done through ajax
6a488035
TO
457 }
458
30c4e065 459 /**
c490a46a 460 * @param array $params
30c4e065
EM
461 *
462 * @return mixed
463 */
00be9182 464 public static function registerInterview($params) {
6a488035
TO
465 $activityId = CRM_Utils_Array::value('activity_id', $params);
466 $surveyTypeId = CRM_Utils_Array::value('activity_type_id', $params);
467 if (!is_array($params) || !$surveyTypeId || !$activityId) {
468 return FALSE;
469 }
470
471 static $surveyFields;
472 if (!is_array($surveyFields)) {
473 $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity',
474 FALSE,
475 FALSE,
476 $surveyTypeId,
477 NULL,
478 FALSE,
479 TRUE
480 );
481 }
482
483 static $statusId;
484 if (!$statusId) {
c9e87d28 485 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
6a488035
TO
486 }
487
488 //format custom fields.
489 $customParams = CRM_Core_BAO_CustomField::postProcess($params,
6a488035
TO
490 $activityId,
491 'Activity'
492 );
493
494 CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
495
496 //process contact data.
be2fb01f 497 $contactParams = $fields = [];
6a488035 498
be2fb01f 499 $contactFieldTypes = array_merge(['Contact'], CRM_Contact_BAO_ContactType::basicTypes());
6a488035
TO
500 $responseFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($params['survey_id']);
501 if (!empty($responseFields)) {
502 foreach ($params as $key => $value) {
503 if (array_key_exists($key, $responseFields)) {
504 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
505 $fields[$key] = $responseFields[$key];
506 $contactParams[$key] = $value;
507 if (isset($params["{$key}_id"])) {
508 $contactParams["{$key}_id"] = $params["{$key}_id"];
509 }
510 }
511 }
512 }
513 }
514
515 $contactId = CRM_Utils_Array::value('voter_id', $params);
516 if ($contactId && !empty($contactParams)) {
517 CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
518 }
519
520 //update activity record.
521 $activity = new CRM_Activity_DAO_Activity();
522 $activity->id = $activityId;
523
524 $activity->selectAdd();
525 $activity->selectAdd('activity_date_time, status_id, result, subject');
526 $activity->find(TRUE);
527 $activity->activity_date_time = date('YmdHis');
528 $activity->status_id = $statusId;
529
a7488080 530 if (!empty($params['activity_date_time'])) {
5ee01db2 531 $activity->activity_date_time = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
6a488035
TO
532 }
533
534 $subject = '';
535 $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
536 if ($surveyTitle) {
58438e5b 537 $subject = $surveyTitle . ' - ';
6a488035
TO
538 }
539 $subject .= ts('Respondent Interview');
540
541 $activity->subject = $subject;
be2fb01f 542 $activityParams = [
5ee01db2
RN
543 'details' => 'details',
544 'result' => 'result',
8ef12e64 545 'engagement_level' => 'activity_engagement_level',
5ee01db2
RN
546 'subject' => 'activity_subject',
547 'status_id' => 'activity_status_id',
8ef12e64 548 'source_contact_id' => 'source_contact',
549 'location' => 'activity_location',
5ee01db2 550 'campaign_id' => 'activity_campaign_id',
21dfd5f5 551 'duration' => 'activity_duration',
be2fb01f 552 ];
5ee01db2 553 foreach ($activityParams as $key => $field) {
a7488080 554 if (!empty($params[$field])) {
5ee01db2
RN
555 $activity->$key = $params[$field];
556 }
557 }
8ef12e64 558
6a488035
TO
559 $activity->save();
560 //really this should use Activity BAO& not be here but refactoring will have to be later
561 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
562 CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
6a488035
TO
563
564 return $activityId;
565 }
566
00be9182 567 public function getVoterIds() {
6a488035
TO
568 if (!$this->_interviewerId) {
569 $session = CRM_Core_Session::singleton();
570 $this->_interviewerId = $session->get('userID');
571 }
572 if (!$this->_surveyId) {
573 // use default survey id
353ffa53
TO
574 $dao = new CRM_Campaign_DAO_Survey();
575 $dao->is_active = 1;
6a488035
TO
576 $dao->is_default = 1;
577 $dao->find(TRUE);
578 $this->_surveyId = $dao->id;
579 }
580
581 $this->_contactIds = $this->get('contactIds');
582 if (!is_array($this->_contactIds)) {
583 //get the survey activities.
c9e87d28 584 $statusIds[] = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
6a488035
TO
585 $surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
586 $this->_interviewerId,
587 $statusIds
588 );
be2fb01f 589 $this->_contactIds = [];
5c2ea586
TO
590 foreach ($surveyActivities as $val) {
591 $this->_contactIds[$val['voter_id']] = $val['voter_id'];
94880218 592 }
6a488035
TO
593 $this->set('contactIds', $this->_contactIds);
594 }
595 }
596
00be9182 597 public function filterVoterIds() {
6a488035
TO
598 //do the cleanup later on.
599 if (!is_array($this->_contactIds)) {
600 return;
601 }
602
603 $profileId = CRM_Campaign_BAO_Survey::getSurveyProfileId($this->_surveyId);
604 if ($profileId) {
605 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
606 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
607 $voterIdCount = count($this->_contactIds);
608
609 //create temporary table to store voter ids.
610 $tempTableName = CRM_Core_DAO::createTempTableName('civicrm_survey_respondent');
893a39a2 611 CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS {$tempTableName}");
6a488035
TO
612 $query = "
613 CREATE TEMPORARY TABLE {$tempTableName} (
614 id int unsigned NOT NULL AUTO_INCREMENT,
8ef12e64 615 survey_contact_id int unsigned NOT NULL,
6a488035
TO
616 PRIMARY KEY ( id )
617);
618";
619 CRM_Core_DAO::executeQuery($query);
620 $batch = 100;
621 $insertedCount = 0;
622 do {
623 $processIds = $this->_contactIds;
624 $insertIds = array_splice($processIds, $insertedCount, $batch);
625 if (!empty($insertIds)) {
8ef12e64 626 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
6a488035
TO
627 VALUES (" . implode('),(', $insertIds) . ');';
628 CRM_Core_DAO::executeQuery($insertSQL);
629 }
630 $insertedCount += $batch;
631 } while ($insertedCount < $voterIdCount);
632
633 $query = "
634 SELECT contact.id as id
8ef12e64 635 FROM civicrm_contact contact
6a488035
TO
636INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
637 WHERE contact.contact_type != %1";
638 $removeContact = CRM_Core_DAO::executeQuery($query,
be2fb01f 639 [1 => [$profileType, 'String']]
6a488035
TO
640 );
641 while ($removeContact->fetch()) {
642 unset($this->_contactIds[$removeContact->id]);
643 }
644 }
645 }
646 }
96025800 647
6a488035 648}