Style - Remove @access
[civicrm-core.git] / CRM / Campaign / Form / Task / Interview.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 */
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.
82 foreach (array(
83 'surveyId', 'contactIds', 'interviewerId') as $fld) {
84 $this->{"_$fld"} = $this->get($fld);
85 }
86 //get the target voter ids.
87 if ($this->_votingTab) {
88 $this->getVoterIds();
89 }
90 }
91 else {
92 parent::preProcess();
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'));
96 }
97
98 if ( $this->_surveyId ) {
99 $params = array('id' => $this->_surveyId);
100 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
101 }
102
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);
107 }
108 elseif ( CRM_Core_OptionGroup::getValue('activity_type','WalkList') == $this->_surveyDetails['activity_type_id'] ) {
109 $orderByParams =
110 array(
111 1 => array(
112 'column' => 'civicrm_address.street_name',
113 'order' => 'ASC',
114 ),
115 2 => array(
116 'column' => 'civicrm_address.street_number%2',
117 'order' => 'ASC',
118 ),
119 3 => array(
120 'column' => 'civicrm_address.street_number',
121 'order' => 'ASC',
122 ),
123 4 => array(
124 'column' => 'contact_a.sort_name',
125 'order' => 'ASC',
126 ),
127 );
128 }
129
130 $orderBy = array();
131 if ( !empty($orderByParams) ) {
132 foreach ( $orderByParams as $key => $val ) {
133 if (!empty($val['column'])) {
134 $orderBy[] = "{$val['column']} {$val['order']}";
135 }
136 }
137 if ( !empty($orderBy) ) {
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) . ' ) ';
145 $sql = "
146 SELECT contact_a.id
147 FROM civicrm_contact contact_a
148 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
149 WHERE {$clause}
150 {$orderClause}";
151
152 $this->_contactIds = array();
153 $dao = CRM_Core_DAO::executeQuery($sql);
154 while ($dao->fetch()) {
155 $this->_contactIds[] = $dao->id;
156 }
157 }
158
159
160 //get the contact read only fields to display.
161 $readOnlyFields = array_merge(array(
162 'contact_type' => '',
163 'sort_name' => ts('Name'),
164 ));
165
166 //get the read only field data.
167 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
168 $returnProperties['contact_sub_type'] = TRUE;
169
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,
173 $this->_contactIds,
174 $this->_interviewerId
175 );
176 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
177 $scheduledStatusId = array_search('Scheduled', $activityStatus);
178
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);
184 if ($activityId &&
185 $statusId &&
186 $scheduledStatusId == $statusId
187 ) {
188 $activityIds["activity_id_{$voterId}"] = $activityId;
189 }
190 else {
191 unset($this->_contactIds[$key]);
192 }
193 }
194
195 //retrieve the contact details.
196 $voterDetails = CRM_Campaign_BAO_Survey::voterDetails($this->_contactIds, $returnProperties);
197
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')
203 )
204 ) {
205 $this->_allowAjaxReleaseButton = TRUE;
206 }
207
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);
218
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);
226 }
227 $this->set('surveyValues', $this->_surveyValues);
228 }
229 $this->assign('surveyValues', $this->_surveyValues);
230
231 $result = CRM_Campaign_BAO_Survey::getReportID($this->_surveyId);
232 $this->assign("instanceId",$result);
233
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);
240 }
241 $this->set('resultOptions', $this->_resultOptions);
242 }
243
244 //validate the required ids.
245 $this->validateIds();
246
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)));
251 }
252
253 //set the title.
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])));
257 }
258
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.'),
264 );
265
266 $errorMessages = array();
267 foreach ($required as $fld => $msg) {
268 if (empty($this->{"_$fld"})) {
269 if (!$this->_votingTab) {
270 CRM_Core_Error::statusBounce($msg);
271 break;
272 }
273 $errorMessages[] = $msg;
274 }
275 }
276
277 $this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
278 }
279
280 /**
281 * Build the form object
282 *
283 *
284 * @return void
285 */
286 public function buildQuickForm() {
287 $this->assign('surveyTypeId', $this->_surveyTypeId);
288
289 $options =
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',
295 );
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'));
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) {
309 if ($field){
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'),
317 array(
318 '' => ts('- select -')) +
319 array_combine($this->_resultOptions, $this->_resultOptions)
320 );
321 }
322
323 $this->add('text', "field[{$contactId}][note]", ts('Note'));
324
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")
330 );
331 }
332 }
333 $this->assign('surveyFields', empty($this->_surveyFields) ? FALSE : $this->_surveyFields);
334
335 //no need to get qf buttons.
336 if ($this->_votingTab) {
337 return;
338 }
339
340 $buttons = array(
341 array('type' => 'cancel',
342 'name' => ts('Done'),
343 'subName' => 'interview',
344 'isDefault' => TRUE,
345 ));
346
347 $buttons[] = array(
348 'type' => 'submit',
349 'name' => ts('Order By >>'),
350 'subName' => 'orderBy',
351 );
352
353 $manageCampaign = CRM_Core_Permission::check('manage campaign');
354 $adminCampaign = CRM_Core_Permission::check('administer CiviCampaign');
355 if ($manageCampaign ||
356 $adminCampaign ||
357 CRM_Core_Permission::check('release campaign contacts')
358 ) {
359 $buttons[] = array(
360 'type' => 'next',
361 'name' => ts('Release Respondents >>'),
362 'subName' => 'interviewToRelease',
363 );
364 }
365 if ($manageCampaign ||
366 $adminCampaign ||
367 CRM_Core_Permission::check('reserve campaign contacts')
368 ) {
369 $buttons[] = array(
370 'type' => 'done',
371 'name' => ts('Reserve More Respondents >>'),
372 'subName' => 'interviewToReserve',
373 );
374 }
375
376 $this->addButtons($buttons);
377 }
378
379 /**
380 * Set default values for the form.
381 *
382 *
383 * @return void
384 */
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;
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
401 if ( CRM_Core_OptionGroup::getValue('activity_type','WalkList') == $this->_surveyDetails['activity_type_id'] ) {
402 $defaults['order_bys'] =
403 array(
404 1 => array(
405 'column' => 'civicrm_address.street_name',
406 'order' => 'ASC',
407 ),
408 2 => array(
409 'column' => 'civicrm_address.street_number%2',
410 'order' => 'ASC',
411 ),
412 3 => array(
413 'column' => 'civicrm_address.street_number',
414 'order' => 'ASC',
415 ),
416 4 => array(
417 'column' => 'contact_a.sort_name',
418 'order' => 'ASC',
419 ),
420 );
421 }
422 else {
423 $defaults['order_bys'] =
424 array(
425 1 =>
426 array(
427 'column' => 'contact_a.sort_name',
428 'order' => 'ASC',
429 ),
430 );
431 }
432 return $defaults;
433 }
434
435 /**
436 * Process the form after the input has been submitted and validated
437 *
438 *
439 * @return void
440 */
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'));
446 }
447 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
448 //get ready to jump to release form.
449 foreach (array(
450 'surveyId', 'contactIds', 'interviewerId') as $fld) {
451 $this->controller->set($fld, $this->{"_$fld"});
452 }
453 $this->controller->set('interviewToRelease', TRUE);
454 }
455
456 // vote is done through ajax
457 return;
458 }
459
460 /**
461 * @param array $params
462 *
463 * @return mixed
464 */
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) {
469 return FALSE;
470 }
471
472 static $surveyFields;
473 if (!is_array($surveyFields)) {
474 $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity',
475 FALSE,
476 FALSE,
477 $surveyTypeId,
478 NULL,
479 FALSE,
480 TRUE
481 );
482 }
483
484 static $statusId;
485 if (!$statusId) {
486 $statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
487 }
488
489 //format custom fields.
490 $customParams = CRM_Core_BAO_CustomField::postProcess($params,
491 $surveyFields,
492 $activityId,
493 'Activity'
494 );
495
496 CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
497
498 //process contact data.
499 $contactParams = $fields = array();
500
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"];
511 }
512 }
513 }
514 }
515 }
516
517 $contactId = CRM_Utils_Array::value('voter_id', $params);
518 if ($contactId && !empty($contactParams)) {
519 CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
520 }
521
522 //update activity record.
523 $activity = new CRM_Activity_DAO_Activity();
524 $activity->id = $activityId;
525
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;
531
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']);
534 }
535
536 $subject = '';
537 $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
538 if ($surveyTitle) {
539 $subject = ts('%1', array(1 => $surveyTitle));
540 $subject .= ' - ';
541 }
542 $subject .= ts('Respondent Interview');
543
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'
555 );
556 foreach ($activityParams as $key => $field) {
557 if (!empty($params[$field])) {
558 $activity->$key = $params[$field];
559 }
560 }
561
562 $activity->save();
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);
566 $activity->free();
567
568 return $activityId;
569 }
570
571 public function getVoterIds() {
572 if (!$this->_interviewerId) {
573 $session = CRM_Core_Session::singleton();
574 $this->_interviewerId = $session->get('userID');
575 }
576 if (!$this->_surveyId) {
577 // use default survey id
578 $dao = new CRM_Campaign_DAO_Survey();
579 $dao->is_active = 1;
580 $dao->is_default = 1;
581 $dao->find(TRUE);
582 $this->_surveyId = $dao->id;
583 }
584
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;
592 }
593 $surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
594 $this->_interviewerId,
595 $statusIds
596 );
597 $this->_contactIds = array();
598 foreach ($surveyActivities as $val) $this->_contactIds[$val['voter_id']] = $val['voter_id'];
599 $this->set('contactIds', $this->_contactIds);
600 }
601 }
602
603 public function filterVoterIds() {
604 //do the cleanup later on.
605 if (!is_array($this->_contactIds)) {
606 return;
607 }
608
609 $profileId = CRM_Campaign_BAO_Survey::getSurveyProfileId($this->_surveyId);
610 if ($profileId) {
611 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
612 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
613 $voterIdCount = count($this->_contactIds);
614
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}");
618 $query = "
619 CREATE TEMPORARY TABLE {$tempTableName} (
620 id int unsigned NOT NULL AUTO_INCREMENT,
621 survey_contact_id int unsigned NOT NULL,
622 PRIMARY KEY ( id )
623 );
624 ";
625 CRM_Core_DAO::executeQuery($query);
626 $batch = 100;
627 $insertedCount = 0;
628 do {
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);
635 }
636 $insertedCount += $batch;
637 } while ($insertedCount < $voterIdCount);
638
639 $query = "
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'))
646 );
647 while ($removeContact->fetch()) {
648 unset($this->_contactIds[$removeContact->id]);
649 }
650 }
651 }
652 }
653 }
654