Merge pull request #3179 from webpartners/master
[civicrm-core.git] / CRM / Campaign / Form / Task / Interview.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class provides the functionality to record voter's interview.
38 */
39 class CRM_Campaign_Form_Task_Interview extends CRM_Campaign_Form_Task {
40
41 /**
42 * the title of the group
43 *
44 * @var string
45 */
46 protected $_title;
47
48 /**
49 * variable to store redirect path
50 *
51 */
52 private $_userContext;
53
54 private $_groupTree;
55
56 private $_surveyFields;
57
58 private $_surveyTypeId;
59
60 private $_interviewerId;
61
62 private $_surveyActivityIds;
63
64 private $_votingTab = FALSE;
65
66 private $_surveyValues;
67
68 private $_resultOptions;
69
70 private $_allowAjaxReleaseButton;
71
72 /**
73 * build all the data structures needed to build the form
74 *
75 * @return void
76 * @access public
77 */
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.
83 foreach (array(
84 'surveyId', 'contactIds', 'interviewerId') as $fld) {
85 $this->{"_$fld"} = $this->get($fld);
86 }
87 //get the target voter ids.
88 if ($this->_votingTab) {
89 $this->getVoterIds();
90 }
91 }
92 else {
93 parent::preProcess();
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'));
97 }
98
99 if ( $this->_surveyId ) {
100 $params = array('id' => $this->_surveyId);
101 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
102 }
103
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);
108 }
109 elseif ( CRM_Core_OptionGroup::getValue('activity_type','WalkList') == $this->_surveyDetails['activity_type_id'] ) {
110 $orderByParams =
111 array(
112 1 =>
113 array(
114 'column' => 'civicrm_address.street_name',
115 'order' => 'ASC',
116 ),
117 2 =>
118 array(
119 'column' => 'civicrm_address.street_number%2',
120 'order' => 'ASC',
121 ),
122 3 =>
123 array(
124 'column' => 'civicrm_address.street_number',
125 'order' => 'ASC',
126 ),
127 4 =>
128 array(
129 'column' => 'contact_a.sort_name',
130 'order' => 'ASC',
131 ),
132 );
133 }
134
135 $orderBy = array();
136 if ( !empty($orderByParams) ) {
137 foreach ( $orderByParams as $key => $val ) {
138 if (!empty($val['column'])) {
139 $orderBy[] = "{$val['column']} {$val['order']}";
140 }
141 }
142 if ( !empty($orderBy) ) {
143 $orderClause = "ORDER BY " . implode(', ', $orderBy);
144 }
145 }
146
147 $this->_contactIds = array_unique($this->_contactIds);
148 if (!empty($this->_contactIds) && $orderClause) {
149 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds) . ' ) ';
150 $sql = "
151 SELECT contact_a.id
152 FROM civicrm_contact contact_a
153 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
154 WHERE {$clause}
155 {$orderClause}";
156
157 $this->_contactIds = array();
158 $dao = CRM_Core_DAO::executeQuery($sql);
159 while ($dao->fetch()) {
160 $this->_contactIds[] = $dao->id;
161 }
162 }
163
164
165 //get the contact read only fields to display.
166 $readOnlyFields = array_merge(array(
167 'contact_type' => '',
168 'sort_name' => ts('Name'),
169 ));
170
171 //get the read only field data.
172 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
173 $returnProperties['contact_sub_type'] = TRUE;
174
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,
178 $this->_contactIds,
179 $this->_interviewerId
180 );
181 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
182 $scheduledStatusId = array_search('Scheduled', $activityStatus);
183
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);
189 if ($activityId &&
190 $statusId &&
191 $scheduledStatusId == $statusId
192 ) {
193 $activityIds["activity_id_{$voterId}"] = $activityId;
194 }
195 else {
196 unset($this->_contactIds[$key]);
197 }
198 }
199
200 //retrieve the contact details.
201 $voterDetails = CRM_Campaign_BAO_Survey::voterDetails($this->_contactIds, $returnProperties);
202
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')
208 )
209 ) {
210 $this->_allowAjaxReleaseButton = TRUE;
211 }
212
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);
223
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);
231 }
232 $this->set('surveyValues', $this->_surveyValues);
233 }
234 $this->assign('surveyValues', $this->_surveyValues);
235
236 $result = CRM_Campaign_BAO_Survey::getReportID($this->_surveyId);
237 $this->assign("instanceId",$result);
238
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);
245 }
246 $this->set('resultOptions', $this->_resultOptions);
247 }
248
249 //validate the required ids.
250 $this->validateIds();
251
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)));
256 }
257
258 //set the title.
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])));
262 }
263
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.'),
269 );
270
271 $errorMessages = array();
272 foreach ($required as $fld => $msg) {
273 if (empty($this->{"_$fld"})) {
274 if (!$this->_votingTab) {
275 CRM_Core_Error::statusBounce($msg);
276 break;
277 }
278 $errorMessages[] = $msg;
279 }
280 }
281
282 $this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
283 }
284
285 /**
286 * Build the form
287 *
288 * @access public
289 *
290 * @return void
291 */
292 function buildQuickForm() {
293 $this->assign('surveyTypeId', $this->_surveyTypeId);
294
295 $options =
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',
301 );
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'));
305 }
306
307 //pickup the uf fields.
308 $this->_surveyFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($this->_surveyId,
309 $this->_surveyTypeId
310 );
311
312 foreach ($this->_contactIds as $contactId) {
313 //build the profile fields.
314 foreach ($this->_surveyFields as $name => $field) {
315 if ($field){
316 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId);
317 }
318 }
319
320 //build the result field.
321 if (!empty($this->_resultOptions)) {
322 $this->add('select', "field[$contactId][result]", ts('Result'),
323 array(
324 '' => ts('- select -')) +
325 array_combine($this->_resultOptions, $this->_resultOptions)
326 );
327 }
328
329 $this->add('text', "field[{$contactId}][note]", ts('Note'));
330
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")
336 );
337 }
338 }
339 $this->assign('surveyFields', empty($this->_surveyFields) ? FALSE : $this->_surveyFields);
340
341 //no need to get qf buttons.
342 if ($this->_votingTab) {
343 return;
344 }
345
346 $buttons = array(
347 array('type' => 'cancel',
348 'name' => ts('Done'),
349 'subName' => 'interview',
350 'isDefault' => TRUE,
351 ));
352
353 $buttons[] = array(
354 'type' => 'submit',
355 'name' => ts('Order By >>'),
356 'subName' => 'orderBy',
357 );
358
359 $manageCampaign = CRM_Core_Permission::check('manage campaign');
360 $adminCampaign = CRM_Core_Permission::check('administer CiviCampaign');
361 if ($manageCampaign ||
362 $adminCampaign ||
363 CRM_Core_Permission::check('release campaign contacts')
364 ) {
365 $buttons[] = array(
366 'type' => 'next',
367 'name' => ts('Release Respondents >>'),
368 'subName' => 'interviewToRelease',
369 );
370 }
371 if ($manageCampaign ||
372 $adminCampaign ||
373 CRM_Core_Permission::check('reserve campaign contacts')
374 ) {
375 $buttons[] = array(
376 'type' => 'done',
377 'name' => ts('Reserve More Respondents >>'),
378 'subName' => 'interviewToReserve',
379 );
380 }
381
382 $this->addButtons($buttons);
383 }
384
385 /**
386 * This function sets the default values for the form.
387 *
388 * @access public
389 *
390 * @return void
391 */
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;
400 }
401 }
402 if (!empty($contactFields)) {
403 foreach ($this->_contactIds as $contactId) {
404 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
405 }
406 }
407
408 if ( CRM_Core_OptionGroup::getValue('activity_type','WalkList') == $this->_surveyDetails['activity_type_id'] ) {
409 $defaults['order_bys'] =
410 array(
411 1 =>
412 array(
413 'column' => 'civicrm_address.street_name',
414 'order' => 'ASC',
415 ),
416 2 =>
417 array(
418 'column' => 'civicrm_address.street_number%2',
419 'order' => 'ASC',
420 ),
421 3 =>
422 array(
423 'column' => 'civicrm_address.street_number',
424 'order' => 'ASC',
425 ),
426 4 =>
427 array(
428 'column' => 'contact_a.sort_name',
429 'order' => 'ASC',
430 ),
431 );
432 }
433 else {
434 $defaults['order_bys'] =
435 array(
436 1 =>
437 array(
438 'column' => 'contact_a.sort_name',
439 'order' => 'ASC',
440 ),
441 );
442 }
443 return $defaults;
444 }
445
446 /**
447 * process the form after the input has been submitted and validated
448 *
449 * @access public
450 *
451 * @return void
452 */
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'));
458 }
459 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
460 //get ready to jump to release form.
461 foreach (array(
462 'surveyId', 'contactIds', 'interviewerId') as $fld) {
463 $this->controller->set($fld, $this->{"_$fld"});
464 }
465 $this->controller->set('interviewToRelease', TRUE);
466 }
467
468 // vote is done through ajax
469 return;
470 }
471
472 /**
473 * @param $params
474 *
475 * @return mixed
476 */
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) {
481 return FALSE;
482 }
483
484 static $surveyFields;
485 if (!is_array($surveyFields)) {
486 $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity',
487 FALSE,
488 FALSE,
489 $surveyTypeId,
490 NULL,
491 FALSE,
492 TRUE
493 );
494 }
495
496 static $statusId;
497 if (!$statusId) {
498 $statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
499 }
500
501 //format custom fields.
502 $customParams = CRM_Core_BAO_CustomField::postProcess($params,
503 $surveyFields,
504 $activityId,
505 'Activity'
506 );
507
508 CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
509
510 //process contact data.
511 $contactParams = $fields = array();
512
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"];
523 }
524 }
525 }
526 }
527 }
528
529 $contactId = CRM_Utils_Array::value('voter_id', $params);
530 if ($contactId && !empty($contactParams)) {
531 CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
532 }
533
534 //update activity record.
535 $activity = new CRM_Activity_DAO_Activity();
536 $activity->id = $activityId;
537
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;
543
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']);
546 }
547
548 $subject = '';
549 $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
550 if ($surveyTitle) {
551 $subject = ts('%1', array(1 => $surveyTitle));
552 $subject .= ' - ';
553 }
554 $subject .= ts('Respondent Interview');
555
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'
567 );
568 foreach ($activityParams as $key => $field) {
569 if (!empty($params[$field])) {
570 $activity->$key = $params[$field];
571 }
572 }
573
574 $activity->save();
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);
578 $activity->free();
579
580 return $activityId;
581 }
582
583 function getVoterIds() {
584 if (!$this->_interviewerId) {
585 $session = CRM_Core_Session::singleton();
586 $this->_interviewerId = $session->get('userID');
587 }
588 if (!$this->_surveyId) {
589 // use default survey id
590 $dao = new CRM_Campaign_DAO_Survey();
591 $dao->is_active = 1;
592 $dao->is_default = 1;
593 $dao->find(TRUE);
594 $this->_surveyId = $dao->id;
595 }
596
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;
604 }
605 $surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
606 $this->_interviewerId,
607 $statusIds
608 );
609 $this->_contactIds = array();
610 foreach ($surveyActivities as $val) $this->_contactIds[$val['voter_id']] = $val['voter_id'];
611 $this->set('contactIds', $this->_contactIds);
612 }
613 }
614
615 function filterVoterIds() {
616 //do the cleanup later on.
617 if (!is_array($this->_contactIds)) {
618 return;
619 }
620
621 $profileId = CRM_Campaign_BAO_Survey::getSurveyProfileId($this->_surveyId);
622 if ($profileId) {
623 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
624 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
625 $voterIdCount = count($this->_contactIds);
626
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}");
630 $query = "
631 CREATE TEMPORARY TABLE {$tempTableName} (
632 id int unsigned NOT NULL AUTO_INCREMENT,
633 survey_contact_id int unsigned NOT NULL,
634 PRIMARY KEY ( id )
635 );
636 ";
637 CRM_Core_DAO::executeQuery($query);
638 $batch = 100;
639 $insertedCount = 0;
640 do {
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);
647 }
648 $insertedCount += $batch;
649 } while ($insertedCount < $voterIdCount);
650
651 $query = "
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'))
658 );
659 while ($removeContact->fetch()) {
660 unset($this->_contactIds[$removeContact->id]);
661 }
662 }
663 }
664 }
665 }
666