3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 require_once 'CRM/Utils/DeprecatedUtils.php';
21 * class to parse membership csv files
23 class CRM_Event_Import_Parser_Participant
extends CRM_Event_Import_Parser
{
24 protected $_mapperKeys;
26 private $_contactIdIndex;
28 private $_participantStatusIndex;
29 private $_participantRoleIndex;
30 private $_eventTitleIndex;
33 * Array of successfully imported participants id's
37 protected $_newParticipants;
42 * @param array $mapperKeys
44 public function __construct(&$mapperKeys) {
45 parent
::__construct();
46 $this->_mapperKeys
= &$mapperKeys;
50 * The initializer code, called before the processing.
52 public function init() {
53 $fields = CRM_Event_BAO_Participant
::importableFields($this->_contactType
, FALSE);
54 $fields['event_id']['title'] = 'Event ID';
55 $eventfields = &CRM_Event_BAO_Event
::fields();
56 $fields['event_title'] = $eventfields['event_title'];
58 foreach ($fields as $name => $field) {
59 $field['type'] = CRM_Utils_Array
::value('type', $field, CRM_Utils_Type
::T_INT
);
60 $field['dataPattern'] = CRM_Utils_Array
::value('dataPattern', $field, '//');
61 $field['headerPattern'] = CRM_Utils_Array
::value('headerPattern', $field, '//');
62 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
65 $this->_newParticipants
= [];
66 $this->setActiveFields($this->_mapperKeys
);
68 // FIXME: we should do this in one place together with Form/MapField.php
69 $this->_contactIdIndex
= -1;
70 $this->_eventIndex
= -1;
71 $this->_participantStatusIndex
= -1;
72 $this->_participantRoleIndex
= -1;
73 $this->_eventTitleIndex
= -1;
76 foreach ($this->_mapperKeys
as $key) {
79 case 'participant_contact_id':
80 $this->_contactIdIndex
= $index;
84 $this->_eventIndex
= $index;
87 case 'participant_status':
88 case 'participant_status_id':
89 $this->_participantStatusIndex
= $index;
92 case 'participant_role_id':
93 $this->_participantRoleIndex
= $index;
97 $this->_eventTitleIndex
= $index;
105 * Handle the values in mapField mode.
107 * @param array $values
108 * The array of values belonging to this line.
112 public function mapField(&$values) {
113 return CRM_Import_Parser
::VALID
;
117 * Handle the values in preview mode.
119 * @param array $values
120 * The array of values belonging to this line.
123 * the result of this processing
125 public function preview(&$values) {
126 return $this->summary($values);
130 * Handle the values in summary mode.
132 * @param array $values
133 * The array of values belonging to this line.
136 * the result of this processing
138 public function summary(&$values) {
139 $erroneousField = NULL;
141 $response = $this->setActiveFieldValues($values, $erroneousField);
142 $errorRequired = FALSE;
145 if ($this->_eventIndex
> -1 && $this->_eventTitleIndex
> -1) {
146 array_unshift($values, ts('Select either EventID OR Event Title'));
147 return CRM_Import_Parser
::ERROR
;
149 elseif ($this->_eventTitleIndex
> -1) {
150 $index = $this->_eventTitleIndex
;
152 elseif ($this->_eventIndex
> -1) {
153 $index = $this->_eventIndex
;
155 $params = &$this->getActiveFieldParams();
157 if (!(($index < 0) ||
($this->_participantStatusIndex
< 0))) {
158 $errorRequired = !CRM_Utils_Array
::value($this->_participantStatusIndex
, $values);
159 if (empty($params['event_id']) && empty($params['event_title'])) {
160 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Event', $missingField);
162 if (empty($params['participant_status_id'])) {
163 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status', $missingField);
167 $errorRequired = TRUE;
168 $missingField = NULL;
170 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Event', $missingField);
172 if ($this->_participantStatusIndex
< 0) {
173 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status', $missingField);
177 if ($errorRequired) {
178 array_unshift($values, ts('Missing required field(s) :') . $missingField);
179 return CRM_Import_Parser
::ERROR
;
182 $errorMessage = NULL;
185 $session = CRM_Core_Session
::singleton();
186 $dateType = $session->get('dateTypes');
188 foreach ($params as $key => $val) {
189 if ($val && ($key == 'participant_register_date')) {
190 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
191 $params[$key] = $dateValue;
194 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Register Date', $errorMessage);
197 elseif ($val && ($key == 'participant_role_id' ||
$key == 'participant_role')) {
198 $roleIDs = CRM_Event_PseudoConstant
::participantRole();
199 $val = explode(',', $val);
200 if ($key == 'participant_role_id') {
201 foreach ($val as $role) {
202 if (!array_key_exists(trim($role), $roleIDs)) {
203 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Role Id', $errorMessage);
209 foreach ($val as $role) {
210 if (!CRM_Contact_Import_Parser_Contact
::in_value(trim($role), $roleIDs)) {
211 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Role', $errorMessage);
217 elseif ($val && (($key == 'participant_status_id') ||
($key == 'participant_status'))) {
218 $statusIDs = CRM_Event_PseudoConstant
::participantStatus();
219 if ($key == 'participant_status_id') {
220 if (!array_key_exists(trim($val), $statusIDs)) {
221 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status Id', $errorMessage);
225 elseif (!CRM_Contact_Import_Parser_Contact
::in_value($val, $statusIDs)) {
226 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status', $errorMessage);
231 //date-Format part ends
233 $params['contact_type'] = 'Participant';
234 //checking error in custom data
235 CRM_Contact_Import_Parser_Contact
::isErrorInCustomData($params, $errorMessage);
238 $tempMsg = "Invalid value for field(s) : $errorMessage";
239 array_unshift($values, $tempMsg);
240 $errorMessage = NULL;
241 return CRM_Import_Parser
::ERROR
;
243 return CRM_Import_Parser
::VALID
;
247 * Handle the values in import mode.
249 * @param int $onDuplicate
250 * The code for what action to take on duplicates.
251 * @param array $values
252 * The array of values belonging to this line.
255 * the result of this processing
257 public function import($onDuplicate, &$values) {
259 // first make sure this is a valid line
260 $response = $this->summary($values);
261 if ($response != CRM_Import_Parser
::VALID
) {
264 $params = &$this->getActiveFieldParams();
265 $session = CRM_Core_Session
::singleton();
266 $dateType = $session->get('dateTypes');
267 $formatted = ['version' => 3];
268 $customFields = CRM_Core_BAO_CustomField
::getFields('Participant');
270 // don't add to recent items, CRM-4399
271 $formatted['skipRecentView'] = TRUE;
273 foreach ($params as $key => $val) {
275 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
276 if ($customFields[$customFieldID]['data_type'] == 'Date') {
277 CRM_Contact_Import_Parser_Contact
::formatCustomDate($params, $formatted, $dateType, $key);
278 unset($params[$key]);
280 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
281 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
284 if ($key == 'participant_register_date') {
285 CRM_Utils_Date
::convertToDefaultDate($params, $dateType, 'participant_register_date');
286 $formatted['participant_register_date'] = CRM_Utils_Date
::processDate($params['participant_register_date']);
291 if (!(!empty($params['participant_role_id']) ||
!empty($params['participant_role']))) {
292 if (!empty($params['event_id'])) {
293 $params['participant_role_id'] = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
296 $eventTitle = $params['event_title'];
297 $params['participant_role_id'] = CRM_Core_DAO
::singleValueQuery('SELECT default_role_id FROM civicrm_event WHERE title = %1', [
298 1 => [$eventTitle, 'String'],
303 //date-Format part ends
304 static $indieFields = NULL;
305 if ($indieFields == NULL) {
306 $indieFields = CRM_Event_BAO_Participant
::import();
310 foreach ($params as $key => $field) {
311 if ($field == NULL ||
$field === '') {
315 $formatValues[$key] = $field;
318 $formatError = $this->formatValues($formatted, $formatValues);
321 array_unshift($values, $formatError['error_message']);
322 return CRM_Import_Parser
::ERROR
;
325 if (!CRM_Utils_Rule
::integer($formatted['event_id'])) {
326 array_unshift($values, ts('Invalid value for Event ID'));
327 return CRM_Import_Parser
::ERROR
;
330 if ($onDuplicate != CRM_Import_Parser
::DUPLICATE_UPDATE
) {
331 $formatted['custom'] = CRM_Core_BAO_CustomField
::postProcess($formatted,
337 if ($formatValues['participant_id']) {
338 $dao = new CRM_Event_BAO_Participant();
339 $dao->id
= $formatValues['participant_id'];
341 $formatted['custom'] = CRM_Core_BAO_CustomField
::postProcess($formatted,
342 $formatValues['participant_id'],
345 if ($dao->find(TRUE)) {
347 'participant' => $formatValues['participant_id'],
348 'userId' => $session->get('userID'),
350 $participantValues = [];
351 //@todo calling api functions directly is not supported
352 $newParticipant = $this->deprecated_participant_check_params($formatted, $participantValues, FALSE);
353 if ($newParticipant['error_message']) {
354 array_unshift($values, $newParticipant['error_message']);
355 return CRM_Import_Parser
::ERROR
;
357 $newParticipant = CRM_Event_BAO_Participant
::create($formatted, $ids);
358 if (!empty($formatted['fee_level'])) {
360 'fee_label' => $formatted['fee_level'],
361 'event_id' => $newParticipant->event_id
,
363 CRM_Price_BAO_LineItem
::syncLineItems($newParticipant->id
, 'civicrm_participant', $newParticipant->fee_amount
, $otherParams);
366 $this->_newParticipant
[] = $newParticipant->id
;
367 return CRM_Import_Parser
::VALID
;
370 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
371 return CRM_Import_Parser
::ERROR
;
376 if ($this->_contactIdIndex
< 0) {
377 $error = $this->checkContactDuplicate($formatValues);
379 if (CRM_Core_Error
::isAPIError($error, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
380 $matchedIDs = explode(',', $error['error_message']['params'][0]);
381 if (count($matchedIDs) >= 1) {
382 foreach ($matchedIDs as $contactId) {
383 $formatted['contact_id'] = $contactId;
384 $formatted['version'] = 3;
385 $newParticipant = $this->deprecated_create_participant_formatted($formatted, $onDuplicate);
390 // Using new Dedupe rule.
392 'contact_type' => $this->_contactType
,
393 'used' => 'Unsupervised',
395 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
398 foreach ($fieldsArray as $value) {
399 if (array_key_exists(trim($value), $params)) {
400 $paramValue = $params[trim($value)];
401 if (is_array($paramValue)) {
402 $disp .= $params[trim($value)][0][trim($value)] . " ";
405 $disp .= $params[trim($value)] . " ";
410 if (!empty($params['external_identifier'])) {
412 $disp .= "AND {$params['external_identifier']}";
415 $disp = $params['external_identifier'];
419 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
420 return CRM_Import_Parser
::ERROR
;
424 if (!empty($formatValues['external_identifier'])) {
425 $checkCid = new CRM_Contact_DAO_Contact();
426 $checkCid->external_identifier
= $formatValues['external_identifier'];
427 $checkCid->find(TRUE);
428 if ($checkCid->id
!= $formatted['contact_id']) {
429 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
430 return CRM_Import_Parser
::ERROR
;
434 $newParticipant = $this->deprecated_create_participant_formatted($formatted, $onDuplicate);
437 if (is_array($newParticipant) && civicrm_error($newParticipant)) {
438 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
) {
440 $contactID = $newParticipant['contactID'] ??
NULL;
441 $participantID = $newParticipant['participantID'] ??
NULL;
442 $url = CRM_Utils_System
::url('civicrm/contact/view/participant',
443 "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE
445 if (is_array($newParticipant['error_message']) &&
446 ($participantID == $newParticipant['error_message']['params'][0])
448 array_unshift($values, $url);
449 return CRM_Import_Parser
::DUPLICATE
;
451 elseif ($newParticipant['error_message']) {
452 array_unshift($values, $newParticipant['error_message']);
453 return CRM_Import_Parser
::ERROR
;
455 return CRM_Import_Parser
::ERROR
;
459 if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
460 $this->_newParticipants
[] = $newParticipant['id'] ??
NULL;
463 return CRM_Import_Parser
::VALID
;
467 * Get the array of successfully imported Participation ids.
471 public function &getImportedParticipations() {
472 return $this->_newParticipants
;
476 * The initializer code, called before the processing
480 public function fini() {
486 * @todo lots of tidy up needed here - very old function relocated.
488 * @param array $values
489 * @param array $params
493 protected function formatValues(&$values, $params) {
494 $fields = CRM_Event_DAO_Participant
::fields();
495 _civicrm_api3_store_values($fields, $params, $values);
497 $customFields = CRM_Core_BAO_CustomField
::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
499 foreach ($params as $key => $value) {
500 // ignore empty values or empty arrays etc
501 if (CRM_Utils_System
::isNull($value)) {
505 // Handling Custom Data
506 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
507 $values[$key] = $value;
508 $type = $customFields[$customFieldID]['html_type'];
509 if (CRM_Core_BAO_CustomField
::isSerialized($customFields[$customFieldID])) {
510 $values[$key] = self
::unserializeCustomValue($customFieldID, $value, $type);
512 elseif ($type == 'Select' ||
$type == 'Radio') {
513 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
514 foreach ($customOption as $customFldID => $customValue) {
515 $val = $customValue['value'] ??
NULL;
516 $label = $customValue['label'] ??
NULL;
517 $label = strtolower($label);
518 $value = strtolower(trim($value));
519 if (($value == $label) ||
($value == strtolower($val))) {
520 $values[$key] = $val;
527 case 'participant_contact_id':
528 if (!CRM_Utils_Rule
::integer($value)) {
529 return civicrm_api3_create_error("contact_id not valid: $value");
531 if (!CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value")) {
532 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
534 $values['contact_id'] = $values['participant_contact_id'];
535 unset($values['participant_contact_id']);
538 case 'participant_register_date':
539 if (!CRM_Utils_Rule
::dateTime($value)) {
540 return civicrm_api3_create_error("$key not a valid date: $value");
545 $id = CRM_Core_DAO
::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
546 $values['event_id'] = $id;
550 if (!CRM_Utils_Rule
::integer($value)) {
551 return civicrm_api3_create_error("Event ID is not valid: $value");
553 $svq = CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_event WHERE id = %1', [
554 1 => [$value, 'Integer'],
557 return civicrm_api3_create_error("Invalid Event ID: There is no event record with event_id = $value.");
561 case 'participant_status_id':
562 if (!CRM_Utils_Rule
::integer($value)) {
563 return civicrm_api3_create_error("Event Status ID is not valid: $value");
567 case 'participant_status':
568 $status = CRM_Event_PseudoConstant
::participantStatus();
569 $values['participant_status_id'] = CRM_Utils_Array
::key($value, $status);
572 case 'participant_role_id':
573 case 'participant_role':
574 $role = CRM_Event_PseudoConstant
::participantRole();
575 $participantRoles = explode(",", $value);
576 foreach ($participantRoles as $k => $v) {
578 if ($key == 'participant_role') {
579 $participantRoles[$k] = CRM_Utils_Array
::key($v, $role);
582 $participantRoles[$k] = $v;
585 $values['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participantRoles);
586 unset($values[$key]);
594 if (array_key_exists('participant_note', $params)) {
595 $values['participant_note'] = $params['participant_note'];
598 // CRM_Event_BAO_Participant::create() handles register_date,
599 // status_id and source. So, if $values contains
600 // participant_register_date, participant_status_id or participant_source,
601 // convert it to register_date, status_id or source
603 'participant_register_date' => 'register_date',
604 'participant_source' => 'source',
605 'participant_status_id' => 'status_id',
606 'participant_role_id' => 'role_id',
607 'participant_fee_level' => 'fee_level',
608 'participant_fee_amount' => 'fee_amount',
609 'participant_id' => 'id',
612 foreach ($changes as $orgVal => $changeVal) {
613 if (isset($values[$orgVal])) {
614 $values[$changeVal] = $values[$orgVal];
615 unset($values[$orgVal]);
623 * @param array $params
624 * @param $onDuplicate
628 * @throws \CiviCRM_API3_Exception
629 * @deprecated - this is part of the import parser not the API & needs to be
633 protected function deprecated_create_participant_formatted($params, $onDuplicate) {
634 if ($onDuplicate != CRM_Import_Parser
::DUPLICATE_NOCHECK
) {
635 CRM_Core_Error
::reset();
636 $error = $this->deprecated_participant_check_params($params, TRUE);
637 if (civicrm_error($error)) {
641 return civicrm_api3('Participant', 'create', $params);
645 * Formatting that was written a long time ago and may not make sense now.
647 * @param array $params
649 * @param bool $checkDuplicate
653 protected function deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
655 // check if participant id is valid or not
656 if (!empty($params['id'])) {
657 $participant = new CRM_Event_BAO_Participant();
658 $participant->id
= $params['id'];
659 if (!$participant->find(TRUE)) {
660 return civicrm_api3_create_error(ts('Participant id is not valid'));
664 // check if contact id is valid or not
665 if (!empty($params['contact_id'])) {
666 $contact = new CRM_Contact_BAO_Contact();
667 $contact->id
= $params['contact_id'];
668 if (!$contact->find(TRUE)) {
669 return civicrm_api3_create_error(ts('Contact id is not valid'));
673 // check that event id is not an template
674 if (!empty($params['event_id'])) {
675 $isTemplate = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
676 if (!empty($isTemplate)) {
677 return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
682 if ($checkDuplicate) {
683 if (CRM_Event_BAO_Participant
::checkDuplicate($params, $result)) {
684 $participantID = array_pop($result);
686 $error = CRM_Core_Error
::createError("Found matching participant record.",
687 CRM_Core_Error
::DUPLICATE_PARTICIPANT
,
688 'Fatal', $participantID
691 return civicrm_api3_create_error($error->pop(),
693 'contactID' => $params['contact_id'],
694 'participantID' => $participantID,