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