copyright and version fixes
[civicrm-core.git] / CRM / Event / Import / Parser / Participant.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36require_once 'CRM/Utils/DeprecatedUtils.php';
37
38/**
39 * class to parse membership csv files
40 */
41class CRM_Event_Import_Parser_Participant extends CRM_Event_Import_Parser {
42 protected $_mapperKeys;
43
44 private $_contactIdIndex;
45
46 //private $_totalAmountIndex;
47
48 private $_eventIndex;
49 private $_participantStatusIndex;
50 private $_participantRoleIndex;
51 private $_eventTitleIndex;
52
53 /**
ceb10dc7 54 * Array of successfully imported participants id's
6a488035
TO
55 *
56 * @array
57 */
58 protected $_newParticipants;
59
60 /**
61 * class constructor
62 */
63 function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
64 parent::__construct();
65 $this->_mapperKeys = &$mapperKeys;
66 }
67
68 /**
69 * the initializer code, called before the processing
70 *
71 * @return void
72 * @access public
73 */
74 function init() {
75 $fields = CRM_Event_BAO_Participant::importableFields($this->_contactType, FALSE);
76 $fields['event_id']['title'] = 'Event ID';
77 $eventfields = &CRM_Event_BAO_Event::fields();
78 $fields['event_title'] = $eventfields['event_title'];
79
80 foreach ($fields as $name => $field) {
81 $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
82 $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
83 $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
84 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
85 }
86
87 $this->_newParticipants = array();
88 $this->setActiveFields($this->_mapperKeys);
89
90 // FIXME: we should do this in one place together with Form/MapField.php
91 $this->_contactIdIndex = -1;
92 $this->_eventIndex = -1;
93 $this->_participantStatusIndex = -1;
94 $this->_participantRoleIndex = -1;
95 $this->_eventTitleIndex = -1;
96
97 $index = 0;
98 foreach ($this->_mapperKeys as $key) {
99
100 switch ($key) {
101 case 'participant_contact_id':
102 $this->_contactIdIndex = $index;
103 break;
104
105 case 'event_id':
106 $this->_eventIndex = $index;
107 break;
108
109 case 'participant_status':
110 case 'participant_status_id':
111 $this->_participantStatusIndex = $index;
112 break;
113
114 case 'participant_role_id':
115 $this->_participantRoleIndex = $index;
116 break;
117
118 case 'event_title':
119 $this->_eventTitleIndex = $index;
120 break;
121 }
122 $index++;
123 }
124 }
125
126 /**
127 * handle the values in mapField mode
128 *
129 * @param array $values the array of values belonging to this line
130 *
131 * @return boolean
132 * @access public
133 */
134 function mapField(&$values) {
a05662ef 135 return CRM_Import_Parser::VALID;
6a488035
TO
136 }
137
138 /**
139 * handle the values in preview mode
140 *
141 * @param array $values the array of values belonging to this line
142 *
143 * @return boolean the result of this processing
144 * @access public
145 */
146 function preview(&$values) {
147 return $this->summary($values);
148 }
149
150 /**
151 * handle the values in summary mode
152 *
153 * @param array $values the array of values belonging to this line
154 *
155 * @return boolean the result of this processing
156 * @access public
157 */
158 function summary(&$values) {
159 $erroneousField = NULL;
160
161 $response = $this->setActiveFieldValues($values, $erroneousField);
162 $errorRequired = FALSE;
163 $index = -1;
164
165 if ($this->_eventIndex > -1 && $this->_eventTitleIndex > -1) {
166 array_unshift($values, ts('Select either EventID OR Event Title'));
a05662ef 167 return CRM_Import_Parser::ERROR;
6a488035
TO
168 }
169 elseif ($this->_eventTitleIndex > -1) {
170 $index = $this->_eventTitleIndex;
171 }
172 elseif ($this->_eventIndex > -1) {
173 $index = $this->_eventIndex;
174 }
175 $params = &$this->getActiveFieldParams();
176
177 if (!(($index < 0) || ($this->_participantStatusIndex < 0))) {
178 $errorRequired = !CRM_Utils_Array::value($this->_participantStatusIndex, $values);
8cc574cf 179 if (empty($params['event_id']) && empty($params['event_title'])) {
719a6fec 180 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Event', $missingField);
6a488035 181 }
a7488080 182 if (empty($params['participant_status_id'])) {
719a6fec 183 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $missingField);
6a488035
TO
184 }
185 }
186 else {
187 $errorRequired = TRUE;
188 $missingField = NULL;
189 if ($index < 0) {
719a6fec 190 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Event', $missingField);
6a488035
TO
191 }
192 if ($this->_participantStatusIndex < 0) {
719a6fec 193 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $missingField);
6a488035
TO
194 }
195 }
196
197 if ($errorRequired) {
198 array_unshift($values, ts('Missing required field(s) :') . $missingField);
a05662ef 199 return CRM_Import_Parser::ERROR;
6a488035
TO
200 }
201
202 $errorMessage = NULL;
203
204 //for date-Formats
205 $session = CRM_Core_Session::singleton();
206 $dateType = $session->get('dateTypes');
207
208 foreach ($params as $key => $val) {
209 if ($val && ($key == 'participant_register_date')) {
210 if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
211 $params[$key] = $dateValue;
212 }
213 else {
719a6fec 214 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
6a488035
TO
215 }
216 }
217 elseif ($val && ($key == 'participant_role_id' || $key == 'participant_role')) {
218 $roleIDs = CRM_Event_PseudoConstant::participantRole();
219 $val = explode(',', $val);
220 if ($key == 'participant_role_id') {
221 foreach ($val as $role) {
222 if (!in_array(trim($role), array_keys($roleIDs))) {
719a6fec 223 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Role Id', $errorMessage);
6a488035
TO
224 break;
225 }
226 }
227 }
228 else {
229 foreach ($val as $role) {
719a6fec
CW
230 if (!CRM_Contact_Import_Parser_Contact::in_value(trim($role), $roleIDs)) {
231 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Role', $errorMessage);
6a488035
TO
232 break;
233 }
234 }
235 }
236 }
237 elseif ($val && (($key == 'participant_status_id') || ($key == 'participant_status'))) {
238 $statusIDs = CRM_Event_PseudoConstant::participantStatus();
239 if ($key == 'participant_status_id') {
240 if (!in_array(trim($val), array_keys($statusIDs))) {
719a6fec 241 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status Id', $errorMessage);
6a488035
TO
242 break;
243 }
244 }
719a6fec
CW
245 elseif (!CRM_Contact_Import_Parser_Contact::in_value($val, $statusIDs)) {
246 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $errorMessage);
6a488035
TO
247 break;
248 }
249 }
250 }
251 //date-Format part ends
252
253 $params['contact_type'] = 'Participant';
254 //checking error in custom data
719a6fec 255 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
6a488035
TO
256
257 if ($errorMessage) {
258 $tempMsg = "Invalid value for field(s) : $errorMessage";
259 array_unshift($values, $tempMsg);
260 $errorMessage = NULL;
a05662ef 261 return CRM_Import_Parser::ERROR;
6a488035 262 }
a05662ef 263 return CRM_Import_Parser::VALID;
6a488035
TO
264 }
265
266 /**
267 * handle the values in import mode
268 *
269 * @param int $onDuplicate the code for what action to take on duplicates
270 * @param array $values the array of values belonging to this line
271 *
272 * @return boolean the result of this processing
273 * @access public
274 */
275 function import($onDuplicate, &$values) {
276
277 // first make sure this is a valid line
278 $response = $this->summary($values);
a05662ef 279 if ($response != CRM_Import_Parser::VALID) {
6a488035
TO
280 return $response;
281 }
282 $params = &$this->getActiveFieldParams();
283 $session = CRM_Core_Session::singleton();
284 $dateType = $session->get('dateTypes');
285 $formatted = array('version' => 3);
286 $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
287
288 // don't add to recent items, CRM-4399
289 $formatted['skipRecentView'] = TRUE;
290
291 foreach ($params as $key => $val) {
292 if ($val) {
293 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
294 if ($customFields[$customFieldID]['data_type'] == 'Date') {
719a6fec 295 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
6a488035
TO
296 unset($params[$key]);
297 }
298 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
299 $params[$key] = CRM_Utils_String::strtoboolstr($val);
300 }
301 }
302 }
303 }
304
8cc574cf 305 if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
a7488080 306 if (!empty($params['event_id'])) {
6a488035
TO
307 $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
308 }
309 else {
310 $eventTitle = $params['event_title'];
311 $qParams = array();
312 $dao = new CRM_Core_DAO();
313 $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '$eventTitle' ",
314 $qParams
315 );
316 }
317 }
318
319 //date-Format part ends
320 static $indieFields = NULL;
321 if ($indieFields == NULL) {
322 $indieFields = CRM_Event_BAO_Participant::import();
323 }
324
325 $formatValues = array();
326 foreach ($params as $key => $field) {
327 if ($field == NULL || $field === '') {
328 continue;
329 }
330
331 $formatValues[$key] = $field;
332 }
333
334 $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
335
336 if ($formatError) {
337 array_unshift($values, $formatError['error_message']);
a05662ef 338 return CRM_Import_Parser::ERROR;
6a488035
TO
339 }
340
341 if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
342 array_unshift($values, ts('Invalid value for Event ID'));
a05662ef 343 return CRM_Import_Parser::ERROR;
6a488035
TO
344 }
345
a05662ef 346 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
6a488035
TO
347 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
348 CRM_Core_DAO::$_nullObject,
349 NULL,
350 'Participant'
351 );
352 }
353 else {
354 if ($formatValues['participant_id']) {
355 $dao = new CRM_Event_BAO_Participant();
356 $dao->id = $formatValues['participant_id'];
357
358 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
359 CRM_Core_DAO::$_nullObject,
360 $formatValues['participant_id'],
361 'Participant'
362 );
363 if ($dao->find(TRUE)) {
364 $ids = array(
365 'participant' => $formatValues['participant_id'],
366 'userId' => $session->get('userID'),
367 );
368 $participantValues = array();
369 //@todo calling api functions directly is not supported
370 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
371 if ($newParticipant['error_message']) {
372 array_unshift($values, $newParticipant['error_message']);
a05662ef 373 return CRM_Import_Parser::ERROR;
6a488035
TO
374 }
375 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
a7488080 376 if (!empty($formatted['fee_level'])) {
6a488035
TO
377 $otherParams = array(
378 'fee_label' => $formatted['fee_level'],
379 'event_id' => $newParticipant->event_id
380 );
381 CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
382 }
383
384 $this->_newParticipant[] = $newParticipant->id;
a05662ef 385 return CRM_Import_Parser::VALID;
6a488035
TO
386 }
387 else {
388 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
a05662ef 389 return CRM_Import_Parser::ERROR;
6a488035
TO
390 }
391 }
392 }
393
394 if ($this->_contactIdIndex < 0) {
395
396 //retrieve contact id using contact dedupe rule
397 $formatValues['contact_type'] = $this->_contactType;
398 $formatValues['version'] = 3;
399 $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
400
401 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
402 $matchedIDs = explode(',', $error['error_message']['params'][0]);
403 if (count($matchedIDs) >= 1) {
404 foreach ($matchedIDs as $contactId) {
405 $formatted['contact_id'] = $contactId;
406 $formatted['version'] = 3;
407 $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
408 }
409 }
410 }
411 else {
412 // Using new Dedupe rule.
413 $ruleParams = array(
414 'contact_type' => $this->_contactType,
415 'used' => 'Unsupervised',
416 );
417 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
418
419 $disp = '';
420 foreach ($fieldsArray as $value) {
421 if (array_key_exists(trim($value), $params)) {
422 $paramValue = $params[trim($value)];
423 if (is_array($paramValue)) {
424 $disp .= $params[trim($value)][0][trim($value)] . " ";
425 }
426 else {
427 $disp .= $params[trim($value)] . " ";
428 }
429 }
430 }
431
a7488080 432 if (!empty($params['external_identifier'])) {
6a488035
TO
433 if ($disp) {
434 $disp .= "AND {$params['external_identifier']}";
435 }
436 else {
437 $disp = $params['external_identifier'];
438 }
439 }
440
441 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
a05662ef 442 return CRM_Import_Parser::ERROR;
6a488035
TO
443 }
444 }
445 else {
a7488080 446 if (!empty($formatValues['external_identifier'])) {
6a488035
TO
447 $checkCid = new CRM_Contact_DAO_Contact();
448 $checkCid->external_identifier = $formatValues['external_identifier'];
449 $checkCid->find(TRUE);
450 if ($checkCid->id != $formatted['contact_id']) {
451 array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
a05662ef 452 return CRM_Import_Parser::ERROR;
6a488035
TO
453 }
454 }
455
456 $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
457 }
458
459 if (is_array($newParticipant) && civicrm_error($newParticipant)) {
a05662ef 460 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
6a488035
TO
461
462 $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
463 $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
464 $url = CRM_Utils_System::url('civicrm/contact/view/participant',
465 "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE
466 );
467 if (is_array($newParticipant['error_message']) &&
468 ($participantID == $newParticipant['error_message']['params'][0])
469 ) {
470 array_unshift($values, $url);
a05662ef 471 return CRM_Import_Parser::DUPLICATE;
6a488035
TO
472 }
473 elseif ($newParticipant['error_message']) {
474 array_unshift($values, $newParticipant['error_message']);
a05662ef 475 return CRM_Import_Parser::ERROR;
6a488035 476 }
a05662ef 477 return CRM_Import_Parser::ERROR;
6a488035
TO
478 }
479 }
480
481 if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
482 $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
483 }
484
a05662ef 485 return CRM_Import_Parser::VALID;
6a488035
TO
486 }
487
488 /**
ceb10dc7 489 * Get the array of successfully imported Participation ids
6a488035
TO
490 *
491 * @return array
492 * @access public
493 */
494 function &getImportedParticipations() {
495 return $this->_newParticipants;
496 }
497
498 /**
499 * the initializer code, called before the processing
500 *
501 * @return void
502 * @access public
503 */
504 function fini() {}
505}
506