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
43 * @param null $mapperLocType
44 * @param null $mapperPhoneType
46 public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
47 parent
::__construct();
48 $this->_mapperKeys
= &$mapperKeys;
52 * The initializer code, called before the processing.
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'];
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']);
67 $this->_newParticipants
= [];
68 $this->setActiveFields($this->_mapperKeys
);
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;
78 foreach ($this->_mapperKeys
as $key) {
81 case 'participant_contact_id':
82 $this->_contactIdIndex
= $index;
86 $this->_eventIndex
= $index;
89 case 'participant_status':
90 case 'participant_status_id':
91 $this->_participantStatusIndex
= $index;
94 case 'participant_role_id':
95 $this->_participantRoleIndex
= $index;
99 $this->_eventTitleIndex
= $index;
107 * Handle the values in mapField mode.
109 * @param array $values
110 * The array of values belonging to this line.
114 public function mapField(&$values) {
115 return CRM_Import_Parser
::VALID
;
119 * Handle the values in preview mode.
121 * @param array $values
122 * The array of values belonging to this line.
125 * the result of this processing
127 public function preview(&$values) {
128 return $this->summary($values);
132 * Handle the values in summary mode.
134 * @param array $values
135 * The array of values belonging to this line.
138 * the result of this processing
140 public function summary(&$values) {
141 $erroneousField = NULL;
143 $response = $this->setActiveFieldValues($values, $erroneousField);
144 $errorRequired = FALSE;
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
;
151 elseif ($this->_eventTitleIndex
> -1) {
152 $index = $this->_eventTitleIndex
;
154 elseif ($this->_eventIndex
> -1) {
155 $index = $this->_eventIndex
;
157 $params = &$this->getActiveFieldParams();
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);
164 if (empty($params['participant_status_id'])) {
165 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status', $missingField);
169 $errorRequired = TRUE;
170 $missingField = NULL;
172 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Event', $missingField);
174 if ($this->_participantStatusIndex
< 0) {
175 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status', $missingField);
179 if ($errorRequired) {
180 array_unshift($values, ts('Missing required field(s) :') . $missingField);
181 return CRM_Import_Parser
::ERROR
;
184 $errorMessage = NULL;
187 $session = CRM_Core_Session
::singleton();
188 $dateType = $session->get('dateTypes');
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;
196 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Register Date', $errorMessage);
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 (!in_array(trim($role), array_keys($roleIDs))) {
205 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Role Id', $errorMessage);
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);
219 elseif ($val && (($key == 'participant_status_id') ||
($key == 'participant_status'))) {
220 $statusIDs = CRM_Event_PseudoConstant
::participantStatus();
221 if ($key == 'participant_status_id') {
222 if (!in_array(trim($val), array_keys($statusIDs))) {
223 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status Id', $errorMessage);
227 elseif (!CRM_Contact_Import_Parser_Contact
::in_value($val, $statusIDs)) {
228 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Participant Status', $errorMessage);
233 //date-Format part ends
235 $params['contact_type'] = 'Participant';
236 //checking error in custom data
237 CRM_Contact_Import_Parser_Contact
::isErrorInCustomData($params, $errorMessage);
240 $tempMsg = "Invalid value for field(s) : $errorMessage";
241 array_unshift($values, $tempMsg);
242 $errorMessage = NULL;
243 return CRM_Import_Parser
::ERROR
;
245 return CRM_Import_Parser
::VALID
;
249 * Handle the values in import mode.
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.
257 * the result of this processing
259 public function import($onDuplicate, &$values) {
261 // first make sure this is a valid line
262 $response = $this->summary($values);
263 if ($response != CRM_Import_Parser
::VALID
) {
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');
272 // don't add to recent items, CRM-4399
273 $formatted['skipRecentView'] = TRUE;
275 foreach ($params as $key => $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]);
282 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
283 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
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']);
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');
298 $eventTitle = $params['event_title'];
300 $dao = new CRM_Core_DAO();
301 $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '$eventTitle' ",
307 //date-Format part ends
308 static $indieFields = NULL;
309 if ($indieFields == NULL) {
310 $indieFields = CRM_Event_BAO_Participant
::import();
314 foreach ($params as $key => $field) {
315 if ($field == NULL ||
$field === '') {
319 $formatValues[$key] = $field;
322 $formatError = $this->formatValues($formatted, $formatValues);
325 array_unshift($values, $formatError['error_message']);
326 return CRM_Import_Parser
::ERROR
;
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
;
334 if ($onDuplicate != CRM_Import_Parser
::DUPLICATE_UPDATE
) {
335 $formatted['custom'] = CRM_Core_BAO_CustomField
::postProcess($formatted,
341 if ($formatValues['participant_id']) {
342 $dao = new CRM_Event_BAO_Participant();
343 $dao->id
= $formatValues['participant_id'];
345 $formatted['custom'] = CRM_Core_BAO_CustomField
::postProcess($formatted,
346 $formatValues['participant_id'],
349 if ($dao->find(TRUE)) {
351 'participant' => $formatValues['participant_id'],
352 'userId' => $session->get('userID'),
354 $participantValues = [];
355 //@todo calling api functions directly is not supported
356 $newParticipant = _civicrm_api3_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
;
361 $newParticipant = CRM_Event_BAO_Participant
::create($formatted, $ids);
362 if (!empty($formatted['fee_level'])) {
364 'fee_label' => $formatted['fee_level'],
365 'event_id' => $newParticipant->event_id
,
367 CRM_Price_BAO_LineItem
::syncLineItems($newParticipant->id
, 'civicrm_participant', $newParticipant->fee_amount
, $otherParams);
370 $this->_newParticipant
[] = $newParticipant->id
;
371 return CRM_Import_Parser
::VALID
;
374 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
375 return CRM_Import_Parser
::ERROR
;
380 if ($this->_contactIdIndex
< 0) {
381 $error = $this->checkContactDuplicate($formatValues);
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 = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
394 // Using new Dedupe rule.
396 'contact_type' => $this->_contactType
,
397 'used' => 'Unsupervised',
399 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
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)] . " ";
409 $disp .= $params[trim($value)] . " ";
414 if (!empty($params['external_identifier'])) {
416 $disp .= "AND {$params['external_identifier']}";
419 $disp = $params['external_identifier'];
423 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
424 return CRM_Import_Parser
::ERROR
;
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
;
438 $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
441 if (is_array($newParticipant) && civicrm_error($newParticipant)) {
442 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
) {
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
449 if (is_array($newParticipant['error_message']) &&
450 ($participantID == $newParticipant['error_message']['params'][0])
452 array_unshift($values, $url);
453 return CRM_Import_Parser
::DUPLICATE
;
455 elseif ($newParticipant['error_message']) {
456 array_unshift($values, $newParticipant['error_message']);
457 return CRM_Import_Parser
::ERROR
;
459 return CRM_Import_Parser
::ERROR
;
463 if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
464 $this->_newParticipants
[] = $newParticipant['id'] ??
NULL;
467 return CRM_Import_Parser
::VALID
;
471 * Get the array of successfully imported Participation ids.
475 public function &getImportedParticipations() {
476 return $this->_newParticipants
;
480 * The initializer code, called before the processing
484 public function fini() {
490 * @todo lots of tidy up needed here - very old function relocated.
492 * @param array $values
493 * @param array $params
497 protected function formatValues(&$values, $params) {
498 $fields = CRM_Event_DAO_Participant
::fields();
499 _civicrm_api3_store_values($fields, $params, $values);
501 $customFields = CRM_Core_BAO_CustomField
::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
503 foreach ($params as $key => $value) {
504 // ignore empty values or empty arrays etc
505 if (CRM_Utils_System
::isNull($value)) {
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);
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;
531 case 'participant_contact_id':
532 if (!CRM_Utils_Rule
::integer($value)) {
533 return civicrm_api3_create_error("contact_id not valid: $value");
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.");
538 $values['contact_id'] = $values['participant_contact_id'];
539 unset($values['participant_contact_id']);
542 case 'participant_register_date':
543 if (!CRM_Utils_Rule
::dateTime($value)) {
544 return civicrm_api3_create_error("$key not a valid date: $value");
549 $id = CRM_Core_DAO
::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
550 $values['event_id'] = $id;
554 if (!CRM_Utils_Rule
::integer($value)) {
555 return civicrm_api3_create_error("Event ID is not valid: $value");
557 $dao = new CRM_Core_DAO();
559 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
563 return civicrm_api3_create_error("Invalid Event ID: There is no event record with event_id = $value.");
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");
573 case 'participant_status':
574 $status = CRM_Event_PseudoConstant
::participantStatus();
575 $values['participant_status_id'] = CRM_Utils_Array
::key($value, $status);
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) {
584 if ($key == 'participant_role') {
585 $participantRoles[$k] = CRM_Utils_Array
::key($v, $role);
588 $participantRoles[$k] = $v;
591 $values['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participantRoles);
592 unset($values[$key]);
600 if (array_key_exists('participant_note', $params)) {
601 $values['participant_note'] = $params['participant_note'];
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
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',
618 foreach ($changes as $orgVal => $changeVal) {
619 if (isset($values[$orgVal])) {
620 $values[$changeVal] = $values[$orgVal];
621 unset($values[$orgVal]);