Merge pull request #23961 from totten/master-mgdphp-caseacttype
[civicrm-core.git] / CRM / Event / Import / Parser / Participant.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18require_once 'CRM/Utils/DeprecatedUtils.php';
19
20/**
21 * class to parse membership csv files
22 */
d60cd664 23class CRM_Event_Import_Parser_Participant extends CRM_Import_Parser {
6a488035
TO
24 protected $_mapperKeys;
25
6a488035 26 /**
ceb10dc7 27 * Array of successfully imported participants id's
6a488035 28 *
90b461f1 29 * @var array
6a488035
TO
30 */
31 protected $_newParticipants;
32
d60cd664
EM
33
34 protected $_fileName;
35
36 /**
37 * Imported file size.
38 *
39 * @var int
40 */
41 protected $_fileSize;
42
43 /**
44 * Separator being used.
45 *
46 * @var string
47 */
48 protected $_separator;
49
50 /**
51 * Total number of lines in file.
52 *
53 * @var int
54 */
55 protected $_lineCount;
56
57 /**
58 * Whether the file has a column header or not
59 *
60 * @var bool
61 */
62 protected $_haveColumnHeader;
63
6a488035 64 /**
fe482240 65 * Class constructor.
54957108 66 *
67 * @param array $mapperKeys
6a488035 68 */
c2d1c1c2 69 public function __construct(&$mapperKeys = []) {
6a488035
TO
70 parent::__construct();
71 $this->_mapperKeys = &$mapperKeys;
72 }
73
3764aead
EM
74 /**
75 * Get information about the provided job.
76 *
77 * - name
78 * - id (generally the same as name)
79 * - label
80 *
81 * @return array
82 */
83 public static function getUserJobInfo(): array {
84 return [
85 'participant_import' => [
86 'id' => 'participant_import',
87 'name' => 'participant_import',
88 'label' => ts('Participant Import'),
89 ],
90 ];
91 }
92
6a488035 93 /**
54957108 94 * The initializer code, called before the processing.
6a488035 95 */
00be9182 96 public function init() {
965259cf 97 unset($this->userJob);
99308da4
EM
98 $this->setFieldMetadata();
99 foreach ($this->importableFieldsMetadata as $name => $field) {
6a488035
TO
100 $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
101 $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
102 $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
103 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
104 }
99308da4 105 }
6a488035 106
6a488035 107 /**
fe482240 108 * Handle the values in preview mode.
6a488035 109 *
d4dd1e85
TO
110 * @param array $values
111 * The array of values belonging to this line.
6a488035 112 *
79d7553f 113 * @return bool
a6c01b45 114 * the result of this processing
6a488035 115 */
00be9182 116 public function preview(&$values) {
6a488035
TO
117 return $this->summary($values);
118 }
119
120 /**
fe482240 121 * Handle the values in summary mode.
6a488035 122 *
d4dd1e85
TO
123 * @param array $values
124 * The array of values belonging to this line.
6a488035 125 *
79d7553f 126 * @return bool
a6c01b45 127 * the result of this processing
6a488035 128 */
00be9182 129 public function summary(&$values) {
99308da4
EM
130 $params = $this->getMappedRow($values);
131 $errors = [];
132 try {
133 $this->validateParams($params);
6a488035 134 }
99308da4
EM
135 catch (CRM_Core_Exception $e) {
136 $errors[] = $e->getMessage();
6a488035 137 }
6a488035 138
99308da4
EM
139 if ($errors) {
140 $tempMsg = "Invalid value for field(s) : " . implode(',', $errors);
6a488035 141 array_unshift($values, $tempMsg);
a05662ef 142 return CRM_Import_Parser::ERROR;
6a488035 143 }
a05662ef 144 return CRM_Import_Parser::VALID;
6a488035
TO
145 }
146
147 /**
fe482240 148 * Handle the values in import mode.
6a488035 149 *
d4dd1e85
TO
150 * @param array $values
151 * The array of values belonging to this line.
6a488035 152 *
79d7553f 153 * @return bool
a6c01b45 154 * the result of this processing
6a488035 155 */
99308da4
EM
156 public function import(&$values) {
157 $rowNumber = (int) ($values[array_key_last($values)]);
4abb6f80 158 try {
99308da4 159 $params = $this->getMappedRow($values);
4abb6f80 160 $session = CRM_Core_Session::singleton();
99308da4 161 $formatted = $params;
4abb6f80
EM
162 // don't add to recent items, CRM-4399
163 $formatted['skipRecentView'] = TRUE;
164
4abb6f80
EM
165 if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
166 if (!empty($params['event_id'])) {
167 $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
168 }
169 else {
170 $eventTitle = $params['event_title'];
171 $params['participant_role_id'] = CRM_Core_DAO::singleValueQuery('SELECT default_role_id FROM civicrm_event WHERE title = %1', [
172 1 => [$eventTitle, 'String'],
173 ]);
174 }
6a488035
TO
175 }
176
4abb6f80
EM
177 $formatValues = [];
178 foreach ($params as $key => $field) {
179 if ($field == NULL || $field === '') {
180 continue;
181 }
6a488035 182
4abb6f80
EM
183 $formatValues[$key] = $field;
184 }
6a488035 185
4abb6f80 186 $formatError = $this->formatValues($formatted, $formatValues);
6a488035 187
4abb6f80 188 if ($formatError) {
99308da4 189 throw new CRM_Core_Exception($formatError['error_message']);
4abb6f80 190 }
6a488035 191
99308da4 192 if (!$this->isUpdateExisting()) {
6a488035 193 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
4abb6f80 194 NULL,
6a488035
TO
195 'Participant'
196 );
4abb6f80
EM
197 }
198 else {
99308da4 199 if (!empty($formatValues['participant_id'])) {
4abb6f80
EM
200 $dao = new CRM_Event_BAO_Participant();
201 $dao->id = $formatValues['participant_id'];
202
203 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
204 $formatValues['participant_id'],
205 'Participant'
206 );
207 if ($dao->find(TRUE)) {
208 $ids = [
209 'participant' => $formatValues['participant_id'],
210 'userId' => $session->get('userID'),
be2fb01f 211 ];
4abb6f80
EM
212 $participantValues = [];
213 //@todo calling api functions directly is not supported
214 $newParticipant = $this->deprecated_participant_check_params($formatted, $participantValues, FALSE);
215 if ($newParticipant['error_message']) {
99308da4 216 throw new CRM_Core_Exception($newParticipant['error_message']);
4abb6f80
EM
217 }
218 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
219 if (!empty($formatted['fee_level'])) {
220 $otherParams = [
221 'fee_label' => $formatted['fee_level'],
222 'event_id' => $newParticipant->event_id,
223 ];
224 CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
225 }
6a488035 226
4abb6f80 227 $this->_newParticipant[] = $newParticipant->id;
99308da4 228 $this->setImportStatus($rowNumber, 'IMPORTED', '', $newParticipant->id);
4abb6f80
EM
229 return CRM_Import_Parser::VALID;
230 }
99308da4 231 throw new CRM_Core_Exception('Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
6a488035
TO
232 }
233 }
6a488035 234
99308da4 235 if (empty($params['contact_id'])) {
4abb6f80 236 $error = $this->checkContactDuplicate($formatValues);
6a488035 237
4abb6f80
EM
238 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
239 $matchedIDs = explode(',', $error['error_message']['params'][0]);
240 if (count($matchedIDs) >= 1) {
241 foreach ($matchedIDs as $contactId) {
242 $formatted['contact_id'] = $contactId;
243 $formatted['version'] = 3;
99308da4 244 $newParticipant = $this->deprecated_create_participant_formatted($formatted);
4abb6f80 245 }
6a488035
TO
246 }
247 }
4abb6f80
EM
248 else {
249 // Using new Dedupe rule.
250 $ruleParams = [
251 'contact_type' => $this->_contactType,
252 'used' => 'Unsupervised',
253 ];
254 $fieldsArray = CRM_Dedupe_BAO_DedupeRule::dedupeRuleFields($ruleParams);
255
256 $disp = '';
257 foreach ($fieldsArray as $value) {
258 if (array_key_exists(trim($value), $params)) {
259 $paramValue = $params[trim($value)];
260 if (is_array($paramValue)) {
261 $disp .= $params[trim($value)][0][trim($value)] . " ";
262 }
263 else {
264 $disp .= $params[trim($value)] . " ";
265 }
266 }
267 }
268
269 if (!empty($params['external_identifier'])) {
270 if ($disp) {
271 $disp .= "AND {$params['external_identifier']}";
6a488035
TO
272 }
273 else {
4abb6f80 274 $disp = $params['external_identifier'];
6a488035
TO
275 }
276 }
99308da4 277 throw new CRM_Core_Exception('No matching Contact found for (' . $disp . ')');
4abb6f80
EM
278 }
279 }
280 else {
281 if (!empty($formatValues['external_identifier'])) {
282 $checkCid = new CRM_Contact_DAO_Contact();
283 $checkCid->external_identifier = $formatValues['external_identifier'];
284 $checkCid->find(TRUE);
285 if ($checkCid->id != $formatted['contact_id']) {
99308da4 286 throw new CRM_Core_Exception('Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
6a488035
TO
287 }
288 }
99308da4 289 $newParticipant = $this->deprecated_create_participant_formatted($formatted);
6a488035 290 }
4abb6f80
EM
291
292 if (is_array($newParticipant) && civicrm_error($newParticipant)) {
99308da4 293 if ($this->isSkipDuplicates()) {
4abb6f80
EM
294
295 $contactID = $newParticipant['contactID'] ?? NULL;
296 $participantID = $newParticipant['participantID'] ?? NULL;
297 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
298 "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE
299 );
300 if (is_array($newParticipant['error_message']) &&
301 ($participantID == $newParticipant['error_message']['params'][0])
302 ) {
303 array_unshift($values, $url);
99308da4 304 $this->setImportStatus($rowNumber, 'DUPLICATE', '');
4abb6f80
EM
305 return CRM_Import_Parser::DUPLICATE;
306 }
307 if ($newParticipant['error_message']) {
99308da4 308 throw new CRM_Core_Exception($newParticipant['error_message']);
4abb6f80 309 }
99308da4 310 throw new CRM_Core_Exception(ts('Unknown error'));
6a488035
TO
311 }
312 }
313
4abb6f80
EM
314 if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
315 $this->_newParticipants[] = $newParticipant['id'] ?? NULL;
6a488035
TO
316 }
317 }
4abb6f80
EM
318 catch (CRM_Core_Exception $e) {
319 array_unshift($values, $e->getMessage());
99308da4 320 $this->setImportStatus($rowNumber, 'ERROR', $e->getMessage());
4abb6f80 321 return CRM_Import_Parser::ERROR;
6a488035 322 }
99308da4
EM
323 catch (CiviCRM_API3_Exception $e) {
324 array_unshift($values, $e->getMessage());
325 $this->setImportStatus($rowNumber, 'ERROR', $e->getMessage());
326 return CRM_Import_Parser::ERROR;
327 }
328 $this->setImportStatus($rowNumber, 'IMPORTED', '');
6a488035
TO
329 }
330
331 /**
fe482240 332 * Get the array of successfully imported Participation ids.
6a488035
TO
333 *
334 * @return array
6a488035 335 */
00be9182 336 public function &getImportedParticipations() {
6a488035
TO
337 return $this->_newParticipants;
338 }
339
c3fc9a44 340 /**
341 * Format values
342 *
343 * @todo lots of tidy up needed here - very old function relocated.
344 *
345 * @param array $values
346 * @param array $params
347 *
348 * @return array|null
349 */
350 protected function formatValues(&$values, $params) {
351 $fields = CRM_Event_DAO_Participant::fields();
352 _civicrm_api3_store_values($fields, $params, $values);
353
354 $customFields = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
355
356 foreach ($params as $key => $value) {
357 // ignore empty values or empty arrays etc
358 if (CRM_Utils_System::isNull($value)) {
359 continue;
360 }
361
362 // Handling Custom Data
363 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
364 $values[$key] = $value;
365 $type = $customFields[$customFieldID]['html_type'];
726e45e7 366 if (CRM_Core_BAO_CustomField::isSerialized($customFields[$customFieldID])) {
be40742b 367 $values[$key] = self::unserializeCustomValue($customFieldID, $value, $type);
c3fc9a44 368 }
369 elseif ($type == 'Select' || $type == 'Radio') {
370 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
371 foreach ($customOption as $customFldID => $customValue) {
9c1bc317
CW
372 $val = $customValue['value'] ?? NULL;
373 $label = $customValue['label'] ?? NULL;
c3fc9a44 374 $label = strtolower($label);
375 $value = strtolower(trim($value));
376 if (($value == $label) || ($value == strtolower($val))) {
377 $values[$key] = $val;
378 }
379 }
380 }
381 }
382
383 switch ($key) {
384 case 'participant_contact_id':
385 if (!CRM_Utils_Rule::integer($value)) {
386 return civicrm_api3_create_error("contact_id not valid: $value");
387 }
08c6b770 388 if (!CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value")) {
c3fc9a44 389 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
390 }
391 $values['contact_id'] = $values['participant_contact_id'];
392 unset($values['participant_contact_id']);
393 break;
394
395 case 'participant_register_date':
396 if (!CRM_Utils_Rule::dateTime($value)) {
397 return civicrm_api3_create_error("$key not a valid date: $value");
398 }
399 break;
400
c3fc9a44 401 case 'participant_status_id':
402 if (!CRM_Utils_Rule::integer($value)) {
403 return civicrm_api3_create_error("Event Status ID is not valid: $value");
404 }
405 break;
406
407 case 'participant_status':
408 $status = CRM_Event_PseudoConstant::participantStatus();
fe7f4414 409 $values['participant_status_id'] = CRM_Utils_Array::key($value, $status);
c3fc9a44 410 break;
411
412 case 'participant_role_id':
413 case 'participant_role':
414 $role = CRM_Event_PseudoConstant::participantRole();
415 $participantRoles = explode(",", $value);
416 foreach ($participantRoles as $k => $v) {
417 $v = trim($v);
418 if ($key == 'participant_role') {
419 $participantRoles[$k] = CRM_Utils_Array::key($v, $role);
420 }
421 else {
422 $participantRoles[$k] = $v;
423 }
424 }
425 $values['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $participantRoles);
426 unset($values[$key]);
427 break;
428
429 default:
430 break;
431 }
432 }
433
434 if (array_key_exists('participant_note', $params)) {
435 $values['participant_note'] = $params['participant_note'];
436 }
437
438 // CRM_Event_BAO_Participant::create() handles register_date,
439 // status_id and source. So, if $values contains
440 // participant_register_date, participant_status_id or participant_source,
441 // convert it to register_date, status_id or source
be2fb01f 442 $changes = [
c3fc9a44 443 'participant_register_date' => 'register_date',
444 'participant_source' => 'source',
445 'participant_status_id' => 'status_id',
446 'participant_role_id' => 'role_id',
447 'participant_fee_level' => 'fee_level',
448 'participant_fee_amount' => 'fee_amount',
449 'participant_id' => 'id',
be2fb01f 450 ];
c3fc9a44 451
452 foreach ($changes as $orgVal => $changeVal) {
453 if (isset($values[$orgVal])) {
454 $values[$changeVal] = $values[$orgVal];
455 unset($values[$orgVal]);
456 }
457 }
458
459 return NULL;
460 }
461
880585a2 462 /**
880585a2 463 * @param array $params
880585a2 464 *
465 * @return array|bool
466 * <type>
4d935ea5 467 * @throws \CiviCRM_API3_Exception
468 * @deprecated - this is part of the import parser not the API & needs to be
469 * moved on out
470 *
880585a2 471 */
99308da4
EM
472 protected function deprecated_create_participant_formatted($params) {
473 if ($this->isIgnoreDuplicates()) {
880585a2 474 CRM_Core_Error::reset();
1a5d4d8a 475 $error = $this->deprecated_participant_check_params($params, TRUE);
880585a2 476 if (civicrm_error($error)) {
477 return $error;
478 }
479 }
4d935ea5 480 return civicrm_api3('Participant', 'create', $params);
880585a2 481 }
482
1a5d4d8a 483 /**
484 * Formatting that was written a long time ago and may not make sense now.
485 *
486 * @param array $params
487 *
488 * @param bool $checkDuplicate
489 *
490 * @return array|bool
491 */
492 protected function deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
493
494 // check if participant id is valid or not
495 if (!empty($params['id'])) {
496 $participant = new CRM_Event_BAO_Participant();
497 $participant->id = $params['id'];
498 if (!$participant->find(TRUE)) {
499 return civicrm_api3_create_error(ts('Participant id is not valid'));
500 }
501 }
502
503 // check if contact id is valid or not
504 if (!empty($params['contact_id'])) {
505 $contact = new CRM_Contact_BAO_Contact();
506 $contact->id = $params['contact_id'];
507 if (!$contact->find(TRUE)) {
508 return civicrm_api3_create_error(ts('Contact id is not valid'));
509 }
510 }
511
512 // check that event id is not an template
513 if (!empty($params['event_id'])) {
514 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
515 if (!empty($isTemplate)) {
516 return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
517 }
518 }
519
520 $result = [];
521 if ($checkDuplicate) {
522 if (CRM_Event_BAO_Participant::checkDuplicate($params, $result)) {
523 $participantID = array_pop($result);
524
525 $error = CRM_Core_Error::createError("Found matching participant record.",
526 CRM_Core_Error::DUPLICATE_PARTICIPANT,
527 'Fatal', $participantID
528 );
529
530 return civicrm_api3_create_error($error->pop(),
531 [
532 'contactID' => $params['contact_id'],
533 'participantID' => $participantID,
534 ]
535 );
536 }
537 }
538 return TRUE;
539 }
540
d60cd664
EM
541 /**
542 * Given a list of the importable field keys that the user has selected
543 * set the active fields array to this list
544 *
545 * @param array $fieldKeys mapped array of values
546 *
547 * @return void
548 */
549 public function setActiveFields($fieldKeys) {
550 $this->_activeFieldCount = count($fieldKeys);
551 foreach ($fieldKeys as $key) {
552 if (empty($this->_fields[$key])) {
553 $this->_activeFields[] = new CRM_Event_Import_Field('', ts('- do not import -'));
554 }
555 else {
556 $this->_activeFields[] = clone($this->_fields[$key]);
557 }
558 }
559 }
560
561 /**
562 * @param string $name
563 * @param $title
564 * @param int $type
565 * @param string $headerPattern
566 * @param string $dataPattern
567 */
568 public function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
569 if (empty($name)) {
570 $this->_fields['doNotImport'] = new CRM_Event_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
571 }
572 else {
573
574 //$tempField = CRM_Contact_BAO_Contact::importableFields('Individual', null );
575 $tempField = CRM_Contact_BAO_Contact::importableFields('All', NULL);
576 if (!array_key_exists($name, $tempField)) {
577 $this->_fields[$name] = new CRM_Event_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
578 }
579 else {
580 $this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern,
581 CRM_Utils_Array::value('hasLocationType', $tempField[$name])
582 );
583 }
584 }
585 }
586
4722138d 587 /**
99308da4 588 * Set up field metadata.
4722138d 589 *
99308da4 590 * @return void
4722138d 591 */
99308da4
EM
592 protected function setFieldMetadata(): void {
593 if (empty($this->importableFieldsMetadata)) {
b4167b7c
EM
594 $fields = array_merge(
595 [
596 '' => ['title' => ts('- do not import -')],
597 'participant_note' => [
598 'title' => ts('Participant Note'),
599 'name' => 'participant_note',
600 'headerPattern' => '/(participant.)?note$/i',
601 'data_type' => CRM_Utils_Type::T_TEXT,
602 'options' => FALSE,
603 ],
604 ],
605 CRM_Event_DAO_Participant::import(),
606 CRM_Core_BAO_CustomField::getFieldsForImport('Participant'),
607 $this->getContactMatchingFields()
608 );
609
610 $fields['participant_contact_id']['title'] .= ' (match to contact)';
611 $fields['participant_contact_id']['html']['label'] = $fields['participant_contact_id']['title'];
612 foreach ($fields as $index => $field) {
613 if (isset($field['name']) && $field['name'] !== $index) {
614 // undo unique names - participant is the primary
615 // entity and no others have conflicting unique names
616 // if we ever added them the should have unique names - v4api style
617 $fields[$field['name']] = $field;
618 unset($fields[$index]);
619 }
620 }
99308da4 621 $this->importableFieldsMetadata = $fields;
4722138d 622 }
99308da4
EM
623 }
624
625 /**
626 * @return array
627 */
628 protected function getRequiredFields(): array {
629 return [['event_id' => ts('Event'), 'status_id' => ts('Status')]];
4722138d
EM
630 }
631
6a488035 632}