Merge pull request #20536 from MegaphoneJon/mailing-96
[civicrm-core.git] / CRM / Event / Import / Parser / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 require_once 'CRM/Utils/DeprecatedUtils.php';
19
20 /**
21 * class to parse membership csv files
22 */
23 class CRM_Event_Import_Parser_Participant extends CRM_Event_Import_Parser {
24 protected $_mapperKeys;
25
26 private $_contactIdIndex;
27 private $_eventIndex;
28 private $_participantStatusIndex;
29 private $_participantRoleIndex;
30 private $_eventTitleIndex;
31
32 /**
33 * Array of successfully imported participants id's
34 *
35 * @var array
36 */
37 protected $_newParticipants;
38
39 /**
40 * Class constructor.
41 *
42 * @param array $mapperKeys
43 * @param null $mapperLocType
44 * @param null $mapperPhoneType
45 */
46 public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
47 parent::__construct();
48 $this->_mapperKeys = &$mapperKeys;
49 }
50
51 /**
52 * The initializer code, called before the processing.
53 */
54 public function init() {
55 $fields = CRM_Event_BAO_Participant::importableFields($this->_contactType, FALSE);
56 $fields['event_id']['title'] = 'Event ID';
57 $eventfields = &CRM_Event_BAO_Event::fields();
58 $fields['event_title'] = $eventfields['event_title'];
59
60 foreach ($fields as $name => $field) {
61 $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
62 $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
63 $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
64 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
65 }
66
67 $this->_newParticipants = [];
68 $this->setActiveFields($this->_mapperKeys);
69
70 // FIXME: we should do this in one place together with Form/MapField.php
71 $this->_contactIdIndex = -1;
72 $this->_eventIndex = -1;
73 $this->_participantStatusIndex = -1;
74 $this->_participantRoleIndex = -1;
75 $this->_eventTitleIndex = -1;
76
77 $index = 0;
78 foreach ($this->_mapperKeys as $key) {
79
80 switch ($key) {
81 case 'participant_contact_id':
82 $this->_contactIdIndex = $index;
83 break;
84
85 case 'event_id':
86 $this->_eventIndex = $index;
87 break;
88
89 case 'participant_status':
90 case 'participant_status_id':
91 $this->_participantStatusIndex = $index;
92 break;
93
94 case 'participant_role_id':
95 $this->_participantRoleIndex = $index;
96 break;
97
98 case 'event_title':
99 $this->_eventTitleIndex = $index;
100 break;
101 }
102 $index++;
103 }
104 }
105
106 /**
107 * Handle the values in mapField mode.
108 *
109 * @param array $values
110 * The array of values belonging to this line.
111 *
112 * @return bool
113 */
114 public function mapField(&$values) {
115 return CRM_Import_Parser::VALID;
116 }
117
118 /**
119 * Handle the values in preview mode.
120 *
121 * @param array $values
122 * The array of values belonging to this line.
123 *
124 * @return bool
125 * the result of this processing
126 */
127 public function preview(&$values) {
128 return $this->summary($values);
129 }
130
131 /**
132 * Handle the values in summary mode.
133 *
134 * @param array $values
135 * The array of values belonging to this line.
136 *
137 * @return bool
138 * the result of this processing
139 */
140 public function summary(&$values) {
141 $erroneousField = NULL;
142
143 $response = $this->setActiveFieldValues($values, $erroneousField);
144 $errorRequired = FALSE;
145 $index = -1;
146
147 if ($this->_eventIndex > -1 && $this->_eventTitleIndex > -1) {
148 array_unshift($values, ts('Select either EventID OR Event Title'));
149 return CRM_Import_Parser::ERROR;
150 }
151 elseif ($this->_eventTitleIndex > -1) {
152 $index = $this->_eventTitleIndex;
153 }
154 elseif ($this->_eventIndex > -1) {
155 $index = $this->_eventIndex;
156 }
157 $params = &$this->getActiveFieldParams();
158
159 if (!(($index < 0) || ($this->_participantStatusIndex < 0))) {
160 $errorRequired = !CRM_Utils_Array::value($this->_participantStatusIndex, $values);
161 if (empty($params['event_id']) && empty($params['event_title'])) {
162 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Event', $missingField);
163 }
164 if (empty($params['participant_status_id'])) {
165 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $missingField);
166 }
167 }
168 else {
169 $errorRequired = TRUE;
170 $missingField = NULL;
171 if ($index < 0) {
172 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Event', $missingField);
173 }
174 if ($this->_participantStatusIndex < 0) {
175 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $missingField);
176 }
177 }
178
179 if ($errorRequired) {
180 array_unshift($values, ts('Missing required field(s) :') . $missingField);
181 return CRM_Import_Parser::ERROR;
182 }
183
184 $errorMessage = NULL;
185
186 //for date-Formats
187 $session = CRM_Core_Session::singleton();
188 $dateType = $session->get('dateTypes');
189
190 foreach ($params as $key => $val) {
191 if ($val && ($key == 'participant_register_date')) {
192 if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
193 $params[$key] = $dateValue;
194 }
195 else {
196 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
197 }
198 }
199 elseif ($val && ($key == 'participant_role_id' || $key == 'participant_role')) {
200 $roleIDs = CRM_Event_PseudoConstant::participantRole();
201 $val = explode(',', $val);
202 if ($key == 'participant_role_id') {
203 foreach ($val as $role) {
204 if (!array_key_exists(trim($role), $roleIDs)) {
205 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Role Id', $errorMessage);
206 break;
207 }
208 }
209 }
210 else {
211 foreach ($val as $role) {
212 if (!CRM_Contact_Import_Parser_Contact::in_value(trim($role), $roleIDs)) {
213 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Role', $errorMessage);
214 break;
215 }
216 }
217 }
218 }
219 elseif ($val && (($key == 'participant_status_id') || ($key == 'participant_status'))) {
220 $statusIDs = CRM_Event_PseudoConstant::participantStatus();
221 if ($key == 'participant_status_id') {
222 if (!array_key_exists(trim($val), $statusIDs)) {
223 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status Id', $errorMessage);
224 break;
225 }
226 }
227 elseif (!CRM_Contact_Import_Parser_Contact::in_value($val, $statusIDs)) {
228 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $errorMessage);
229 break;
230 }
231 }
232 }
233 //date-Format part ends
234
235 $params['contact_type'] = 'Participant';
236 //checking error in custom data
237 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
238
239 if ($errorMessage) {
240 $tempMsg = "Invalid value for field(s) : $errorMessage";
241 array_unshift($values, $tempMsg);
242 $errorMessage = NULL;
243 return CRM_Import_Parser::ERROR;
244 }
245 return CRM_Import_Parser::VALID;
246 }
247
248 /**
249 * Handle the values in import mode.
250 *
251 * @param int $onDuplicate
252 * The code for what action to take on duplicates.
253 * @param array $values
254 * The array of values belonging to this line.
255 *
256 * @return bool
257 * the result of this processing
258 */
259 public function import($onDuplicate, &$values) {
260
261 // first make sure this is a valid line
262 $response = $this->summary($values);
263 if ($response != CRM_Import_Parser::VALID) {
264 return $response;
265 }
266 $params = &$this->getActiveFieldParams();
267 $session = CRM_Core_Session::singleton();
268 $dateType = $session->get('dateTypes');
269 $formatted = ['version' => 3];
270 $customFields = CRM_Core_BAO_CustomField::getFields('Participant');
271
272 // don't add to recent items, CRM-4399
273 $formatted['skipRecentView'] = TRUE;
274
275 foreach ($params as $key => $val) {
276 if ($val) {
277 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
278 if ($customFields[$customFieldID]['data_type'] == 'Date') {
279 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
280 unset($params[$key]);
281 }
282 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
283 $params[$key] = CRM_Utils_String::strtoboolstr($val);
284 }
285 }
286 if ($key == 'participant_register_date') {
287 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
288 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
289 }
290 }
291 }
292
293 if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
294 if (!empty($params['event_id'])) {
295 $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
296 }
297 else {
298 $eventTitle = $params['event_title'];
299 $qParams = [];
300 $dao = new CRM_Core_DAO();
301 $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '$eventTitle' ",
302 $qParams
303 );
304 }
305 }
306
307 //date-Format part ends
308 static $indieFields = NULL;
309 if ($indieFields == NULL) {
310 $indieFields = CRM_Event_BAO_Participant::import();
311 }
312
313 $formatValues = [];
314 foreach ($params as $key => $field) {
315 if ($field == NULL || $field === '') {
316 continue;
317 }
318
319 $formatValues[$key] = $field;
320 }
321
322 $formatError = $this->formatValues($formatted, $formatValues);
323
324 if ($formatError) {
325 array_unshift($values, $formatError['error_message']);
326 return CRM_Import_Parser::ERROR;
327 }
328
329 if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
330 array_unshift($values, ts('Invalid value for Event ID'));
331 return CRM_Import_Parser::ERROR;
332 }
333
334 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
335 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
336 NULL,
337 'Participant'
338 );
339 }
340 else {
341 if ($formatValues['participant_id']) {
342 $dao = new CRM_Event_BAO_Participant();
343 $dao->id = $formatValues['participant_id'];
344
345 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
346 $formatValues['participant_id'],
347 'Participant'
348 );
349 if ($dao->find(TRUE)) {
350 $ids = [
351 'participant' => $formatValues['participant_id'],
352 'userId' => $session->get('userID'),
353 ];
354 $participantValues = [];
355 //@todo calling api functions directly is not supported
356 $newParticipant = $this->deprecated_participant_check_params($formatted, $participantValues, FALSE);
357 if ($newParticipant['error_message']) {
358 array_unshift($values, $newParticipant['error_message']);
359 return CRM_Import_Parser::ERROR;
360 }
361 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
362 if (!empty($formatted['fee_level'])) {
363 $otherParams = [
364 'fee_label' => $formatted['fee_level'],
365 'event_id' => $newParticipant->event_id,
366 ];
367 CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
368 }
369
370 $this->_newParticipant[] = $newParticipant->id;
371 return CRM_Import_Parser::VALID;
372 }
373 else {
374 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
375 return CRM_Import_Parser::ERROR;
376 }
377 }
378 }
379
380 if ($this->_contactIdIndex < 0) {
381 $error = $this->checkContactDuplicate($formatValues);
382
383 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
384 $matchedIDs = explode(',', $error['error_message']['params'][0]);
385 if (count($matchedIDs) >= 1) {
386 foreach ($matchedIDs as $contactId) {
387 $formatted['contact_id'] = $contactId;
388 $formatted['version'] = 3;
389 $newParticipant = $this->deprecated_create_participant_formatted($formatted, $onDuplicate);
390 }
391 }
392 }
393 else {
394 // Using new Dedupe rule.
395 $ruleParams = [
396 'contact_type' => $this->_contactType,
397 'used' => 'Unsupervised',
398 ];
399 $fieldsArray = CRM_Dedupe_BAO_DedupeRule::dedupeRuleFields($ruleParams);
400
401 $disp = '';
402 foreach ($fieldsArray as $value) {
403 if (array_key_exists(trim($value), $params)) {
404 $paramValue = $params[trim($value)];
405 if (is_array($paramValue)) {
406 $disp .= $params[trim($value)][0][trim($value)] . " ";
407 }
408 else {
409 $disp .= $params[trim($value)] . " ";
410 }
411 }
412 }
413
414 if (!empty($params['external_identifier'])) {
415 if ($disp) {
416 $disp .= "AND {$params['external_identifier']}";
417 }
418 else {
419 $disp = $params['external_identifier'];
420 }
421 }
422
423 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
424 return CRM_Import_Parser::ERROR;
425 }
426 }
427 else {
428 if (!empty($formatValues['external_identifier'])) {
429 $checkCid = new CRM_Contact_DAO_Contact();
430 $checkCid->external_identifier = $formatValues['external_identifier'];
431 $checkCid->find(TRUE);
432 if ($checkCid->id != $formatted['contact_id']) {
433 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
434 return CRM_Import_Parser::ERROR;
435 }
436 }
437
438 $newParticipant = $this->deprecated_create_participant_formatted($formatted, $onDuplicate);
439 }
440
441 if (is_array($newParticipant) && civicrm_error($newParticipant)) {
442 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
443
444 $contactID = $newParticipant['contactID'] ?? NULL;
445 $participantID = $newParticipant['participantID'] ?? NULL;
446 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
447 "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE
448 );
449 if (is_array($newParticipant['error_message']) &&
450 ($participantID == $newParticipant['error_message']['params'][0])
451 ) {
452 array_unshift($values, $url);
453 return CRM_Import_Parser::DUPLICATE;
454 }
455 elseif ($newParticipant['error_message']) {
456 array_unshift($values, $newParticipant['error_message']);
457 return CRM_Import_Parser::ERROR;
458 }
459 return CRM_Import_Parser::ERROR;
460 }
461 }
462
463 if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
464 $this->_newParticipants[] = $newParticipant['id'] ?? NULL;
465 }
466
467 return CRM_Import_Parser::VALID;
468 }
469
470 /**
471 * Get the array of successfully imported Participation ids.
472 *
473 * @return array
474 */
475 public function &getImportedParticipations() {
476 return $this->_newParticipants;
477 }
478
479 /**
480 * The initializer code, called before the processing
481 *
482 * @return void
483 */
484 public function fini() {
485 }
486
487 /**
488 * Format values
489 *
490 * @todo lots of tidy up needed here - very old function relocated.
491 *
492 * @param array $values
493 * @param array $params
494 *
495 * @return array|null
496 */
497 protected function formatValues(&$values, $params) {
498 $fields = CRM_Event_DAO_Participant::fields();
499 _civicrm_api3_store_values($fields, $params, $values);
500
501 $customFields = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
502
503 foreach ($params as $key => $value) {
504 // ignore empty values or empty arrays etc
505 if (CRM_Utils_System::isNull($value)) {
506 continue;
507 }
508
509 // Handling Custom Data
510 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
511 $values[$key] = $value;
512 $type = $customFields[$customFieldID]['html_type'];
513 if (CRM_Core_BAO_CustomField::isSerialized($customFields[$customFieldID])) {
514 $values[$key] = self::unserializeCustomValue($customFieldID, $value, $type);
515 }
516 elseif ($type == 'Select' || $type == 'Radio') {
517 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
518 foreach ($customOption as $customFldID => $customValue) {
519 $val = $customValue['value'] ?? NULL;
520 $label = $customValue['label'] ?? NULL;
521 $label = strtolower($label);
522 $value = strtolower(trim($value));
523 if (($value == $label) || ($value == strtolower($val))) {
524 $values[$key] = $val;
525 }
526 }
527 }
528 }
529
530 switch ($key) {
531 case 'participant_contact_id':
532 if (!CRM_Utils_Rule::integer($value)) {
533 return civicrm_api3_create_error("contact_id not valid: $value");
534 }
535 if (!CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value")) {
536 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
537 }
538 $values['contact_id'] = $values['participant_contact_id'];
539 unset($values['participant_contact_id']);
540 break;
541
542 case 'participant_register_date':
543 if (!CRM_Utils_Rule::dateTime($value)) {
544 return civicrm_api3_create_error("$key not a valid date: $value");
545 }
546 break;
547
548 case 'event_title':
549 $id = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
550 $values['event_id'] = $id;
551 break;
552
553 case 'event_id':
554 if (!CRM_Utils_Rule::integer($value)) {
555 return civicrm_api3_create_error("Event ID is not valid: $value");
556 }
557 $dao = new CRM_Core_DAO();
558 $qParams = [];
559 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
560 $qParams
561 );
562 if (!$svq) {
563 return civicrm_api3_create_error("Invalid Event ID: There is no event record with event_id = $value.");
564 }
565 break;
566
567 case 'participant_status_id':
568 if (!CRM_Utils_Rule::integer($value)) {
569 return civicrm_api3_create_error("Event Status ID is not valid: $value");
570 }
571 break;
572
573 case 'participant_status':
574 $status = CRM_Event_PseudoConstant::participantStatus();
575 $values['participant_status_id'] = CRM_Utils_Array::key($value, $status);
576 break;
577
578 case 'participant_role_id':
579 case 'participant_role':
580 $role = CRM_Event_PseudoConstant::participantRole();
581 $participantRoles = explode(",", $value);
582 foreach ($participantRoles as $k => $v) {
583 $v = trim($v);
584 if ($key == 'participant_role') {
585 $participantRoles[$k] = CRM_Utils_Array::key($v, $role);
586 }
587 else {
588 $participantRoles[$k] = $v;
589 }
590 }
591 $values['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $participantRoles);
592 unset($values[$key]);
593 break;
594
595 default:
596 break;
597 }
598 }
599
600 if (array_key_exists('participant_note', $params)) {
601 $values['participant_note'] = $params['participant_note'];
602 }
603
604 // CRM_Event_BAO_Participant::create() handles register_date,
605 // status_id and source. So, if $values contains
606 // participant_register_date, participant_status_id or participant_source,
607 // convert it to register_date, status_id or source
608 $changes = [
609 'participant_register_date' => 'register_date',
610 'participant_source' => 'source',
611 'participant_status_id' => 'status_id',
612 'participant_role_id' => 'role_id',
613 'participant_fee_level' => 'fee_level',
614 'participant_fee_amount' => 'fee_amount',
615 'participant_id' => 'id',
616 ];
617
618 foreach ($changes as $orgVal => $changeVal) {
619 if (isset($values[$orgVal])) {
620 $values[$changeVal] = $values[$orgVal];
621 unset($values[$orgVal]);
622 }
623 }
624
625 return NULL;
626 }
627
628 /**
629 * @param array $params
630 * @param $onDuplicate
631 *
632 * @return array|bool
633 * <type>
634 * @throws \CiviCRM_API3_Exception
635 * @deprecated - this is part of the import parser not the API & needs to be
636 * moved on out
637 *
638 */
639 protected function deprecated_create_participant_formatted($params, $onDuplicate) {
640 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
641 CRM_Core_Error::reset();
642 $error = $this->deprecated_participant_check_params($params, TRUE);
643 if (civicrm_error($error)) {
644 return $error;
645 }
646 }
647 return civicrm_api3('Participant', 'create', $params);
648 }
649
650 /**
651 * Formatting that was written a long time ago and may not make sense now.
652 *
653 * @param array $params
654 *
655 * @param bool $checkDuplicate
656 *
657 * @return array|bool
658 */
659 protected function deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
660
661 // check if participant id is valid or not
662 if (!empty($params['id'])) {
663 $participant = new CRM_Event_BAO_Participant();
664 $participant->id = $params['id'];
665 if (!$participant->find(TRUE)) {
666 return civicrm_api3_create_error(ts('Participant id is not valid'));
667 }
668 }
669
670 // check if contact id is valid or not
671 if (!empty($params['contact_id'])) {
672 $contact = new CRM_Contact_BAO_Contact();
673 $contact->id = $params['contact_id'];
674 if (!$contact->find(TRUE)) {
675 return civicrm_api3_create_error(ts('Contact id is not valid'));
676 }
677 }
678
679 // check that event id is not an template
680 if (!empty($params['event_id'])) {
681 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
682 if (!empty($isTemplate)) {
683 return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
684 }
685 }
686
687 $result = [];
688 if ($checkDuplicate) {
689 if (CRM_Event_BAO_Participant::checkDuplicate($params, $result)) {
690 $participantID = array_pop($result);
691
692 $error = CRM_Core_Error::createError("Found matching participant record.",
693 CRM_Core_Error::DUPLICATE_PARTICIPANT,
694 'Fatal', $participantID
695 );
696
697 return civicrm_api3_create_error($error->pop(),
698 [
699 'contactID' => $params['contact_id'],
700 'participantID' => $participantID,
701 ]
702 );
703 }
704 }
705 return TRUE;
706 }
707
708 }