notice fixes, CRM-14782
[civicrm-core.git] / CRM / Contact / Import / Parser / Contact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 //@todo calling api functions directly is not supported
37 require_once 'api/v3/utils.php';
38 require_once 'api/v3/Contact.php';
39
40 /**
41 * class to parse contact csv files
42 */
43 class CRM_Contact_Import_Parser_Contact extends CRM_Contact_Import_Parser {
44 protected $_mapperKeys;
45 protected $_mapperLocType;
46 protected $_mapperPhoneType;
47 protected $_mapperImProvider;
48 protected $_mapperWebsiteType;
49 protected $_mapperRelated;
50 protected $_mapperRelatedContactType;
51 protected $_mapperRelatedContactDetails;
52 protected $_mapperRelatedContactEmailType;
53 protected $_mapperRelatedContactImProvider;
54 protected $_mapperRelatedContactWebsiteType;
55 protected $_relationships;
56
57 protected $_emailIndex;
58 protected $_firstNameIndex;
59 protected $_lastNameIndex;
60
61 protected $_householdNameIndex;
62 protected $_organizationNameIndex;
63
64 protected $_allEmails;
65
66 protected $_phoneIndex;
67 protected $_updateWithId;
68 protected $_retCode;
69
70 protected $_externalIdentifierIndex;
71 protected $_allExternalIdentifiers;
72 protected $_parseStreetAddress;
73
74 /**
75 * Array of successfully imported contact id's
76 *
77 * @array
78 */
79 protected $_newContacts;
80
81 /**
82 * line count id
83 *
84 * @var int
85 */
86 protected $_lineCount;
87
88 /**
89 * Array of successfully imported related contact id's
90 *
91 * @array
92 */
93 protected $_newRelatedContacts;
94
95 /**
96 * array of all the contacts whose street addresses are not parsed
97 * of this import process
98 * @var array
99 */
100 protected $_unparsedStreetAddressContacts;
101
102 /**
103 * class constructor
104 */
105 function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL, $mapperImProvider = NULL, $mapperRelated = NULL, $mapperRelatedContactType = NULL, $mapperRelatedContactDetails = NULL, $mapperRelatedContactLocType = NULL, $mapperRelatedContactPhoneType = NULL, $mapperRelatedContactImProvider = NULL,
106 $mapperWebsiteType = NULL, $mapperRelatedContactWebsiteType = NULL
107 ) {
108 parent::__construct();
109 $this->_mapperKeys = &$mapperKeys;
110 $this->_mapperLocType = &$mapperLocType;
111 $this->_mapperPhoneType = &$mapperPhoneType;
112 $this->_mapperWebsiteType = $mapperWebsiteType;
113 // get IM service provider type id for contact
114 $this->_mapperImProvider = &$mapperImProvider;
115 $this->_mapperRelated = &$mapperRelated;
116 $this->_mapperRelatedContactType = &$mapperRelatedContactType;
117 $this->_mapperRelatedContactDetails = &$mapperRelatedContactDetails;
118 $this->_mapperRelatedContactLocType = &$mapperRelatedContactLocType;
119 $this->_mapperRelatedContactPhoneType = &$mapperRelatedContactPhoneType;
120 $this->_mapperRelatedContactWebsiteType = $mapperRelatedContactWebsiteType;
121 // get IM service provider type id for related contact
122 $this->_mapperRelatedContactImProvider = &$mapperRelatedContactImProvider;
123 }
124
125 /**
126 * the initializer code, called before the processing
127 *
128 * @return void
129 * @access public
130 */
131 function init() {
132 $contactFields = CRM_Contact_BAO_Contact::importableFields($this->_contactType);
133 // exclude the address options disabled in the Address Settings
134 $fields = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
135
136 //CRM-5125
137 //supporting import for contact subtypes
138 $csType = NULL;
139 if (!empty($this->_contactSubType)) {
140 //custom fields for sub type
141 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($this->_contactSubType);
142
143 if (!empty($subTypeFields)) {
144 foreach ($subTypeFields as $customSubTypeField => $details) {
145 $fields[$customSubTypeField] = $details;
146 }
147 }
148 }
149
150 //Relationship importables
151 $this->_relationships = $relations =
152 CRM_Contact_BAO_Relationship::getContactRelationshipType(
153 NULL, NULL, NULL, $this->_contactType,
154 FALSE, 'label', TRUE, $this->_contactSubType
155 );
156 asort($relations);
157
158 foreach ($relations as $key => $var) {
159 list($type) = explode('_', $key);
160 $relationshipType[$key]['title'] = $var;
161 $relationshipType[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
162 $relationshipType[$key]['import'] = TRUE;
163 $relationshipType[$key]['relationship_type_id'] = $type;
164 $relationshipType[$key]['related'] = TRUE;
165 }
166
167 if (!empty($relationshipType)) {
168 $fields = array_merge($fields, array(
169 'related' => array(
170 'title' => ts('- related contact info -'),
171 ),
172 ), $relationshipType);
173 }
174
175 foreach ($fields as $name => $field) {
176 $this->addField($name, $field['title'], CRM_Utils_Array::value('type', $field), CRM_Utils_Array::value('headerPattern', $field), CRM_Utils_Array::value('dataPattern', $field), CRM_Utils_Array::value('hasLocationType', $field));
177 }
178
179 $this->_newContacts = array();
180
181 $this->setActiveFields($this->_mapperKeys);
182 $this->setActiveFieldLocationTypes($this->_mapperLocType);
183 $this->setActiveFieldPhoneTypes($this->_mapperPhoneType);
184 $this->setActiveFieldWebsiteTypes($this->_mapperWebsiteType);
185 //set active fields of IM provider of contact
186 $this->setActiveFieldImProviders($this->_mapperImProvider);
187
188 //related info
189 $this->setActiveFieldRelated($this->_mapperRelated);
190 $this->setActiveFieldRelatedContactType($this->_mapperRelatedContactType);
191 $this->setActiveFieldRelatedContactDetails($this->_mapperRelatedContactDetails);
192 $this->setActiveFieldRelatedContactLocType($this->_mapperRelatedContactLocType);
193 $this->setActiveFieldRelatedContactPhoneType($this->_mapperRelatedContactPhoneType);
194 $this->setActiveFieldRelatedContactWebsiteType($this->_mapperRelatedContactWebsiteType);
195 //set active fields of IM provider of related contact
196 $this->setActiveFieldRelatedContactImProvider($this->_mapperRelatedContactImProvider);
197
198 $this->_phoneIndex = -1;
199 $this->_emailIndex = -1;
200 $this->_firstNameIndex = -1;
201 $this->_lastNameIndex = -1;
202 $this->_householdNameIndex = -1;
203 $this->_organizationNameIndex = -1;
204 $this->_externalIdentifierIndex = -1;
205
206 $index = 0;
207 foreach ($this->_mapperKeys as $key) {
208 if (substr($key, 0, 5) == 'email' && substr($key, 0, 14) != 'email_greeting') {
209 $this->_emailIndex = $index;
210 $this->_allEmails = array();
211 }
212 if (substr($key, 0, 5) == 'phone') {
213 $this->_phoneIndex = $index;
214 }
215 if ($key == 'first_name') {
216 $this->_firstNameIndex = $index;
217 }
218 if ($key == 'last_name') {
219 $this->_lastNameIndex = $index;
220 }
221 if ($key == 'household_name') {
222 $this->_householdNameIndex = $index;
223 }
224 if ($key == 'organization_name') {
225 $this->_organizationNameIndex = $index;
226 }
227
228 if ($key == 'external_identifier') {
229 $this->_externalIdentifierIndex = $index;
230 $this->_allExternalIdentifiers = array();
231 }
232 $index++;
233 }
234
235 $this->_updateWithId = FALSE;
236 if (in_array('id', $this->_mapperKeys) || ($this->_externalIdentifierIndex >= 0 && in_array($this->_onDuplicate, array(
237 CRM_Import_Parser::DUPLICATE_UPDATE,
238 CRM_Import_Parser::DUPLICATE_FILL,
239 )))) {
240 $this->_updateWithId = TRUE;
241 }
242
243 $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
244 }
245
246 /**
247 * handle the values in mapField mode
248 *
249 * @param array $values the array of values belonging to this line
250 *
251 * @return boolean
252 * @access public
253 */
254 function mapField(&$values) {
255 return CRM_Import_Parser::VALID;
256 }
257
258 /**
259 * handle the values in preview mode
260 *
261 * @param array $values the array of values belonging to this line
262 *
263 * @return boolean the result of this processing
264 * @access public
265 */
266 function preview(&$values) {
267 return $this->summary($values);
268 }
269
270 /**
271 * handle the values in summary mode
272 *
273 * @param array $values the array of values belonging to this line
274 *
275 * @return boolean the result of this processing
276 * @access public
277 */
278 function summary(&$values) {
279 $erroneousField = NULL;
280 $response = $this->setActiveFieldValues($values, $erroneousField);
281
282 $errorMessage = NULL;
283 $errorRequired = FALSE;
284 switch ($this->_contactType) {
285 case 'Individual':
286 $missingNames = array();
287 if ($this->_firstNameIndex < 0 || !CRM_Utils_Array::value($this->_firstNameIndex, $values)) {
288 $errorRequired = TRUE;
289 $missingNames[] = ts('First Name');
290 }
291 if ($this->_lastNameIndex < 0 || !CRM_Utils_Array::value($this->_lastNameIndex, $values)) {
292 $errorRequired = TRUE;
293 $missingNames[] = ts('Last Name');
294 }
295 if ($errorRequired) {
296 $and = ' ' . ts('and') . ' ';
297 $errorMessage = ts('Missing required fields:') . ' ' . implode($and, $missingNames);
298 }
299 break;
300
301 case 'Household':
302 if ($this->_householdNameIndex < 0 || !CRM_Utils_Array::value($this->_householdNameIndex, $values)) {
303 $errorRequired = TRUE;
304 $errorMessage = ts('Missing required fields:') . ' ' . ts('Household Name');
305 }
306 break;
307
308 case 'Organization':
309 if ($this->_organizationNameIndex < 0 || !CRM_Utils_Array::value($this->_organizationNameIndex, $values)) {
310 $errorRequired = TRUE;
311 $errorMessage = ts('Missing required fields:') . ' ' . ts('Organization Name');
312 }
313 break;
314 }
315
316 $statusFieldName = $this->_statusFieldName;
317
318 if ($this->_emailIndex >= 0) {
319 /* If we don't have the required fields, bail */
320
321 if ($this->_contactType == 'Individual' && !$this->_updateWithId) {
322 if ($errorRequired && !CRM_Utils_Array::value($this->_emailIndex, $values)) {
323 if ($errorMessage) {
324 $errorMessage .= ' ' . ts('OR') . ' ' . ts('Email Address');
325 }
326 else {
327 $errorMessage = ts('Missing required field:') . ' ' . ts('Email Address');
328 }
329 array_unshift($values, $errorMessage);
330 $importRecordParams = array(
331 $statusFieldName => 'ERROR',
332 "${statusFieldName}Msg" => $errorMessage,
333 );
334 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
335
336 return CRM_Import_Parser::ERROR;
337 }
338 }
339
340 $email = CRM_Utils_Array::value($this->_emailIndex, $values);
341 if ($email) {
342 /* If the email address isn't valid, bail */
343
344 if (!CRM_Utils_Rule::email($email)) {
345 $errorMessage = ts('Invalid Email address');
346 array_unshift($values, $errorMessage);
347 $importRecordParams = array(
348 $statusFieldName => 'ERROR',
349 "${statusFieldName}Msg" => $errorMessage,
350 );
351 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
352
353 return CRM_Import_Parser::ERROR;
354 }
355
356 /* otherwise, count it and move on */
357 $this->_allEmails[$email] = $this->_lineCount;
358 }
359 }
360 elseif ($errorRequired && !$this->_updateWithId) {
361 if ($errorMessage) {
362 $errorMessage .= ' ' . ts('OR') . ' ' . ts('Email Address');
363 }
364 else {
365 $errorMessage = ts('Missing required field:') . ' ' . ts('Email Address');
366 }
367 array_unshift($values, $errorMessage);
368 $importRecordParams = array(
369 $statusFieldName => 'ERROR',
370 "${statusFieldName}Msg" => $errorMessage,
371 );
372 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
373
374 return CRM_Import_Parser::ERROR;
375 }
376
377 //check for duplicate external Identifier
378 $externalID = CRM_Utils_Array::value($this->_externalIdentifierIndex, $values);
379 if ($externalID) {
380 /* If it's a dupe,external Identifier */
381
382 if ($externalDupe = CRM_Utils_Array::value($externalID, $this->_allExternalIdentifiers)) {
383 $errorMessage = ts('External Identifier conflicts with record %1', array(1 => $externalDupe));
384 array_unshift($values, $errorMessage);
385 $importRecordParams = array(
386 $statusFieldName => 'ERROR',
387 "${statusFieldName}Msg" => $errorMessage,
388 );
389 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
390 return CRM_Import_Parser::ERROR;
391 }
392 //otherwise, count it and move on
393 $this->_allExternalIdentifiers[$externalID] = $this->_lineCount;
394 }
395
396 //Checking error in custom data
397 $params = &$this->getActiveFieldParams();
398 $params['contact_type'] = $this->_contactType;
399 //date-format part ends
400
401 $errorMessage = NULL;
402
403 //CRM-5125
404 //add custom fields for contact sub type
405 $csType = NULL;
406 if (!empty($this->_contactSubType)) {
407 $csType = $this->_contactSubType;
408 }
409
410 //checking error in custom data
411 $this->isErrorInCustomData($params, $errorMessage, $csType, $this->_relationships);
412
413 //checking error in core data
414 $this->isErrorInCoreData($params, $errorMessage);
415 if ($errorMessage) {
416 $tempMsg = "Invalid value for field(s) : $errorMessage";
417 // put the error message in the import record in the DB
418 $importRecordParams = array(
419 $statusFieldName => 'ERROR',
420 "${statusFieldName}Msg" => $tempMsg,
421 );
422 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
423 array_unshift($values, $tempMsg);
424 $errorMessage = NULL;
425 return CRM_Import_Parser::ERROR;
426 }
427
428 //if user correcting errors by walking back
429 //need to reset status ERROR msg to null
430 //now currently we are having valid data.
431 $importRecordParams = array(
432 $statusFieldName => 'NEW',
433 );
434 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
435
436 return CRM_Import_Parser::VALID;
437 }
438
439 /**
440 * handle the values in import mode
441 *
442 * @param int $onDuplicate the code for what action to take on duplicates
443 * @param array $values the array of values belonging to this line
444 *
445 * @return boolean the result of this processing
446 * @access public
447 */
448 function import($onDuplicate, &$values, $doGeocodeAddress = FALSE) {
449 $config = CRM_Core_Config::singleton();
450 $this->_unparsedStreetAddressContacts = array();
451 if (!$doGeocodeAddress) {
452 // CRM-5854, reset the geocode method to null to prevent geocoding
453 $config->geocodeMethod = NULL;
454 }
455
456 // first make sure this is a valid line
457 //$this->_updateWithId = false;
458 $response = $this->summary($values);
459 $statusFieldName = $this->_statusFieldName;
460
461 if ($response != CRM_Import_Parser::VALID) {
462 $importRecordParams = array(
463 $statusFieldName => 'INVALID',
464 "${statusFieldName}Msg" => "Invalid (Error Code: $response)",
465 );
466 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
467 return $response;
468 }
469
470 $params = &$this->getActiveFieldParams();
471 $formatted = array(
472 'contact_type' => $this->_contactType,
473 );
474
475 static $contactFields = NULL;
476 if ($contactFields == NULL) {
477 $contactFields = CRM_Contact_DAO_Contact::import();
478 }
479
480 //check if external identifier exists in database
481 if (CRM_Utils_Array::value('external_identifier', $params) && (CRM_Utils_Array::value('id', $params) || in_array($onDuplicate, array(
482 CRM_Import_Parser::DUPLICATE_SKIP,
483 CRM_Import_Parser::DUPLICATE_NOCHECK,
484 )))) {
485
486 if ($internalCid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
487 if ($internalCid != CRM_Utils_Array::value('id', $params)) {
488 $errorMessage = ts('External Identifier already exists in database.');
489 array_unshift($values, $errorMessage);
490 $importRecordParams = array(
491 $statusFieldName => 'ERROR',
492 "${statusFieldName}Msg" => $errorMessage,
493 );
494 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
495 return CRM_Import_Parser::DUPLICATE;
496 }
497 }
498 }
499
500 if (!empty($this->_contactSubType)) {
501 $params['contact_sub_type'] = $this->_contactSubType;
502 }
503
504 if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) {
505 if (CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType, FALSE, 'label')) {
506 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType, FALSE, NULL);
507 $params['contact_sub_type'] = array_search($subType, $subTypes);
508 }
509 elseif (!CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType)) {
510 $message = "Mismatched or Invalid Contact SubType.";
511 array_unshift($values, $message);
512 return CRM_Import_Parser::NO_MATCH;
513 }
514 }
515
516 //get contact id to format common data in update/fill mode,
517 //if external identifier is present, CRM-4423
518 if ($this->_updateWithId && !CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
519 if ($cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) {
520 $formatted['id'] = $cid;
521 }
522 }
523
524 //format common data, CRM-4062
525 $this->formatCommonData($params, $formatted, $contactFields);
526
527 $relationship = FALSE;
528 $createNewContact = TRUE;
529 // Support Match and Update Via Contact ID
530 if ($this->_updateWithId) {
531 $createNewContact = FALSE;
532 if (!CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) {
533 if ($cid) {
534 $params['id'] = $cid;
535 }
536 else {
537 //update contact if dedupe found contact id, CRM-4148
538 $dedupeParams = $formatted;
539
540 //special case to check dedupe if external id present.
541 //if we send external id dedupe will stop.
542 unset($dedupeParams['external_identifier']);
543 require_once 'CRM/Utils/DeprecatedUtils.php';
544 $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($dedupeParams);
545 if (CRM_Core_Error::isAPIError($checkDedupe, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
546 $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
547 if (count($matchingContactIds) == 1) {
548 $params['id'] = array_pop($matchingContactIds);
549 }
550 else {
551 $message = "More than one matching contact found for given criteria.";
552 array_unshift($values, $message);
553 $this->_retCode = CRM_Import_Parser::NO_MATCH;
554 }
555 }
556 else {
557 $createNewContact = TRUE;
558 }
559 }
560 }
561
562 $error = _civicrm_api3_deprecated_duplicate_formatted_contact($formatted);
563 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
564 $matchedIDs = explode(',', $error['error_message']['params'][0]);
565 if (count($matchedIDs) >= 1) {
566 $updateflag = TRUE;
567 foreach ($matchedIDs as $contactId) {
568 if ($params['id'] == $contactId) {
569 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
570
571 if ($formatted['contact_type'] == $contactType) {
572 //validation of subtype for update mode
573 //CRM-5125
574 $contactSubType = NULL;
575 if (CRM_Utils_Array::value('contact_sub_type', $params)) {
576 $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
577 }
578
579 if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) && $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
580
581 $message = "Mismatched contact SubTypes :";
582 array_unshift($values, $message);
583 $updateflag = FALSE;
584 $this->_retCode = CRM_Import_Parser::NO_MATCH;
585 }
586 else {
587 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId, FALSE, $this->_dedupeRuleGroupID);
588 $updateflag = FALSE;
589 $this->_retCode = CRM_Import_Parser::VALID;
590 }
591 }
592 else {
593 $message = "Mismatched contact Types :";
594 array_unshift($values, $message);
595 $updateflag = FALSE;
596 $this->_retCode = CRM_Import_Parser::NO_MATCH;
597 }
598 }
599 }
600 if ($updateflag) {
601 $message = "Mismatched contact IDs OR Mismatched contact Types :";
602 array_unshift($values, $message);
603 $this->_retCode = CRM_Import_Parser::NO_MATCH;
604 }
605 }
606 }
607 else {
608 $contactType = NULL;
609 if (CRM_Utils_Array::value('id', $params)) {
610 $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
611 if ($contactType) {
612 if ($formatted['contact_type'] == $contactType) {
613 //validation of subtype for update mode
614 //CRM-5125
615 $contactSubType = NULL;
616 if (CRM_Utils_Array::value('contact_sub_type', $params)) {
617 $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
618 }
619
620 if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) && $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) {
621
622 $message = "Mismatched contact SubTypes :";
623 array_unshift($values, $message);
624 $this->_retCode = CRM_Import_Parser::NO_MATCH;
625 }
626 else {
627 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], FALSE, $this->_dedupeRuleGroupID);
628 $this->_retCode = CRM_Import_Parser::VALID;
629 }
630 }
631 else {
632 $message = "Mismatched contact Types :";
633 array_unshift($values, $message);
634 $this->_retCode = CRM_Import_Parser::NO_MATCH;
635 }
636 }
637 else {
638 // we should avoid multiple errors for single record
639 // since we have already retCode and we trying to force again.
640 if ($this->_retCode != CRM_Import_Parser::NO_MATCH) {
641 $message = "No contact found for this contact ID:" . $params['id'];
642 array_unshift($values, $message);
643 $this->_retCode = CRM_Import_Parser::NO_MATCH;
644 }
645 }
646 }
647 else {
648 //CRM-4148
649 //now we want to create new contact on update/fill also.
650 $createNewContact = TRUE;
651 }
652 }
653
654 if (isset($newContact) && is_a($newContact, 'CRM_Contact_BAO_Contact')) {
655 $relationship = TRUE;
656 }
657 elseif (is_a($error, 'CRM_Core_Error')) {
658 $newContact = $error;
659 $relationship = TRUE;
660 }
661 }
662
663 //fixed CRM-4148
664 //now we create new contact in update/fill mode also.
665 $contactID = NULL;
666 if ($createNewContact || ($this->_retCode != CRM_Import_Parser::NO_MATCH && $this->_updateWithId)) {
667
668 //CRM-4430, don't carry if not submitted.
669 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $name) {
670 if (!empty($formatted[$name])) {
671 $options = CRM_Contact_BAO_Contact::buildOptions($name, 'get');
672 if (!isset($options[$formatted[$name]])) {
673 $formatted[$name] = CRM_Utils_Array::key((string) $formatted[$name], $options);
674 }
675 }
676 }
677 if ($this->_updateWithId && !empty($params['id'])) {
678 $contactID = $params['id'];
679 }
680 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactID, TRUE, $this->_dedupeRuleGroupID);
681 }
682
683 if (isset($newContact) && is_object($newContact) && ($newContact instanceof CRM_Contact_BAO_Contact)) {
684 $relationship = TRUE;
685 $newContact = clone($newContact);
686 $contactID = $newContact->id;
687 $this->_newContacts[] = $contactID;
688
689 //get return code if we create new contact in update mode, CRM-4148
690 if ($this->_updateWithId) {
691 $this->_retCode = CRM_Import_Parser::VALID;
692 }
693 }
694 elseif (isset($newContact) && CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
695 // if duplicate, no need of further processing
696 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
697 $errorMessage = "Skipping duplicate record";
698 array_unshift($values, $errorMessage);
699 $importRecordParams = array(
700 $statusFieldName => 'DUPLICATE',
701 "${statusFieldName}Msg" => $errorMessage,
702 );
703 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
704 return CRM_Import_Parser::DUPLICATE;
705 }
706
707 $relationship = TRUE;
708 # see CRM-10433 - might return comma separate list of all dupes
709 $dupeContactIDs = explode(',',$newContact['error_message']['params'][0]);
710 $dupeCount = count($dupeContactIDs);
711 $contactID = array_pop($dupeContactIDs);
712 // check to see if we had more than one duplicate contact id.
713 // if we have more than one, the record will be rejected below
714 if ($dupeCount == 1) {
715 // there was only one dupe, we will continue normally...
716 if (!in_array($contactID, $this->_newContacts)) {
717 $this->_newContacts[] = $contactID;
718 }
719 }
720 }
721
722 if ($contactID) {
723 // call import hook
724 $currentImportID = end($values);
725
726 $hookParams = array(
727 'contactID' => $contactID,
728 'importID' => $currentImportID,
729 'importTempTable' => $this->_tableName,
730 'fieldHeaders' => $this->_mapperKeys,
731 'fields' => $this->_activeFields,
732 );
733
734 CRM_Utils_Hook::import('Contact', 'process', $this, $hookParams);
735 }
736
737 if ($relationship) {
738 $primaryContactId = NULL;
739 if (CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
740 if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) {
741 $primaryContactId = $newContact['error_message']['params'][0];
742 }
743 }
744 else {
745 $primaryContactId = $newContact->id;
746 }
747
748 if ((CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT) || is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) {
749
750 //relationship contact insert
751 foreach ($params as $key => $field) {
752 list($id, $first, $second) = CRM_Utils_System::explode('_', $key, 3);
753 if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) {
754 continue;
755 }
756
757 $relationType = new CRM_Contact_DAO_RelationshipType();
758 $relationType->id = $id;
759 $relationType->find(TRUE);
760 $direction = "contact_sub_type_$second";
761
762 $formatting = array(
763 'contact_type' => $params[$key]['contact_type'],
764 );
765
766 //set subtype for related contact CRM-5125
767 if (isset($relationType->$direction)) {
768 //validation of related contact subtype for update mode
769 if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->$direction) {
770 $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact");
771 array_unshift($values, $errorMessage);
772 return CRM_Import_Parser::NO_MATCH;
773 }
774 else {
775 $formatting['contact_sub_type'] = $relationType->$direction;
776 }
777 }
778 $relationType->free();
779
780 $contactFields = NULL;
781 $contactFields = CRM_Contact_DAO_Contact::import();
782
783 //Relation on the basis of External Identifier.
784 if (!CRM_Utils_Array::value('id', $params[$key]) && !empty($params[$key]['external_identifier'])) {
785 $params[$key]['id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier');
786 }
787 // check for valid related contact id in update/fill mode, CRM-4424
788 if (in_array($onDuplicate, array(
789 CRM_Import_Parser::DUPLICATE_UPDATE,
790 CRM_Import_Parser::DUPLICATE_FILL,
791 )) && CRM_Utils_Array::value('id', $params[$key])) {
792 $relatedContactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type');
793 if (!$relatedContactType) {
794 $errorMessage = ts("No contact found for this related contact ID: %1", array(1 => $params[$key]['id']));
795 array_unshift($values, $errorMessage);
796 return CRM_Import_Parser::NO_MATCH;
797 }
798 else {
799 //validation of related contact subtype for update mode
800 //CRM-5125
801 $relatedCsType = NULL;
802 if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
803 $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type');
804 }
805
806 if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params[$key]['id'], $relatedCsType) &&
807 $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
808 $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact ID: %1", array(1 => $params[$key]['id']));
809 array_unshift($values, $errorMessage);
810 return CRM_Import_Parser::NO_MATCH;
811 }
812 else {
813 // get related contact id to format data in update/fill mode,
814 //if external identifier is present, CRM-4423
815 $formatting['id'] = $params[$key]['id'];
816 }
817 }
818 }
819
820 //format common data, CRM-4062
821 $this->formatCommonData($field, $formatting, $contactFields);
822
823 //do we have enough fields to create related contact.
824 $allowToCreate = $this->checkRelatedContactFields($key, $formatting);
825
826 if (!$allowToCreate) {
827 $errorMessage = ts('Related contact required fields are missing.');
828 array_unshift($values, $errorMessage);
829 return CRM_Import_Parser::NO_MATCH;
830 }
831
832 //fixed for CRM-4148
833 if (CRM_Utils_Array::value('id', $params[$key])) {
834 $contact = array(
835 'contact_id' => $params[$key]['id'],
836 );
837 $defaults = array();
838 $relatedNewContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
839 }
840 else {
841 $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, NULL, FALSE);
842 }
843
844 if (is_object($relatedNewContact) || ($relatedNewContact instanceof CRM_Contact_BAO_Contact)) {
845 $relatedNewContact = clone($relatedNewContact);
846 }
847
848 $matchedIDs = array();
849 // To update/fill contact, get the matching contact Ids if duplicate contact found
850 // otherwise get contact Id from object of related contact
851 if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) {
852 if (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
853 $matchedIDs = explode(',', $relatedNewContact['error_message']['params'][0]);
854 }
855 else {
856 $errorMessage = $relatedNewContact['error_message'];
857 array_unshift($values, $errorMessage);
858 $importRecordParams = array(
859 $statusFieldName => 'ERROR',
860 "${statusFieldName}Msg" => $errorMessage,
861 );
862 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
863 return CRM_Import_Parser::ERROR;
864 }
865 }
866 else {
867 $matchedIDs[] = $relatedNewContact->id;
868 }
869 // update/fill related contact after getting matching Contact Ids, CRM-4424
870 if (in_array($onDuplicate, array(
871 CRM_Import_Parser::DUPLICATE_UPDATE,
872 CRM_Import_Parser::DUPLICATE_FILL,
873 ))) {
874 //validation of related contact subtype for update mode
875 //CRM-5125
876 $relatedCsType = NULL;
877 if (CRM_Utils_Array::value('contact_sub_type', $formatting)) {
878 $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type');
879 }
880
881 if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($matchedIDs[0], $relatedCsType) && $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) {
882 $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.");
883 array_unshift($values, $errorMessage);
884 return CRM_Import_Parser::NO_MATCH;
885 }
886 else {
887 $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]);
888 }
889 }
890 static $relativeContact = array();
891 if (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
892 if (count($matchedIDs) >= 1) {
893 $relContactId = $matchedIDs[0];
894 //add relative contact to count during update & fill mode.
895 //logic to make count distinct by contact id.
896 if ($this->_newRelatedContacts || !empty($relativeContact)) {
897 $reContact = array_keys($relativeContact, $relContactId);
898
899 if (empty($reContact)) {
900 $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
901 }
902 }
903 else {
904 $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
905 }
906 }
907 }
908 else {
909 $relContactId = $relatedNewContact->id;
910 $this->_newRelatedContacts[] = $relativeContact[] = $relContactId;
911 }
912
913 if (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT) || ($relatedNewContact instanceof CRM_Contact_BAO_Contact)) {
914 //fix for CRM-1993.Checks for duplicate related contacts
915 if (count($matchedIDs) >= 1) {
916 //if more than one duplicate contact
917 //found, create relationship with first contact
918 // now create the relationship record
919 $relationParams = array();
920 $relationParams = array(
921 'relationship_type_id' => $key,
922 'contact_check' => array(
923 $relContactId => 1,
924 ),
925 'is_active' => 1,
926 'skipRecentView' => TRUE,
927 );
928
929 // we only handle related contact success, we ignore failures for now
930 // at some point wold be nice to have related counts as separate
931 $relationIds = array(
932 'contact' => $primaryContactId,
933 );
934
935 list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
936
937 if ($valid || $duplicate) {
938 $relationIds['contactTarget'] = $relContactId;
939 $action = ($duplicate) ? CRM_Core_Action::UPDATE : CRM_Core_Action::ADD;
940 CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds, $action);
941 }
942
943 //handle current employer, CRM-3532
944 if ($valid) {
945 $allRelationships = CRM_Core_PseudoConstant::relationshipType('name');
946 $relationshipTypeId = str_replace(array(
947 '_a_b',
948 '_b_a',
949 ), array(
950 '',
951 '',
952 ), $key);
953 $relationshipType = str_replace($relationshipTypeId . '_', '', $key);
954 $orgId = $individualId = NULL;
955 if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') {
956 $orgId = $relContactId;
957 $individualId = $primaryContactId;
958 }
959 elseif ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') {
960 $orgId = $primaryContactId;
961 $individualId = $relContactId;
962 }
963 if ($orgId && $individualId) {
964 $currentEmpParams[$individualId] = $orgId;
965 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams);
966 }
967 }
968 }
969 }
970 }
971 }
972 }
973 if ($this->_updateWithId) {
974 //return warning if street address is unparsed, CRM-5886
975 return $this->processMessage($values, $statusFieldName, $this->_retCode);
976 }
977 //dupe checking
978 if (is_array($newContact) && civicrm_error($newContact)) {
979 $code = NULL;
980
981 if (($code = CRM_Utils_Array::value('code', $newContact['error_message'])) && ($code == CRM_Core_Error::DUPLICATE_CONTACT)) {
982 $urls = array();
983 // need to fix at some stage and decide if the error will return an
984 // array or string, crude hack for now
985 if (is_array($newContact['error_message']['params'][0])) {
986 $cids = $newContact['error_message']['params'][0];
987 }
988 else {
989 $cids = explode(',', $newContact['error_message']['params'][0]);
990 }
991
992 foreach ($cids as $cid) {
993 $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, TRUE);
994 }
995
996 $url_string = implode("\n", $urls);
997
998 // If we duplicate more than one record, skip no matter what
999 if (count($cids) > 1) {
1000 $errorMessage = ts('Record duplicates multiple contacts');
1001 $importRecordParams = array(
1002 $statusFieldName => 'ERROR',
1003 "${statusFieldName}Msg" => $errorMessage,
1004 );
1005
1006 //combine error msg to avoid mismatch between error file columns.
1007 $errorMessage .= "\n" . $url_string;
1008 array_unshift($values, $errorMessage);
1009 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1010 return CRM_Import_Parser::ERROR;
1011 }
1012
1013 // Params only had one id, so shift it out
1014 $contactId = array_shift($cids);
1015 $cid = NULL;
1016
1017 $vals = array('contact_id' => $contactId);
1018
1019 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_REPLACE) {
1020 civicrm_api('contact', 'delete', $vals);
1021 $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']);
1022 }
1023 elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
1024 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
1025 }
1026 elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
1027 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
1028 }
1029 // else skip does nothing and just returns an error code.
1030
1031
1032 if ($cid) {
1033 $contact = array(
1034 'contact_id' => $cid,
1035 );
1036 $defaults = array();
1037 $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
1038 }
1039
1040 if (civicrm_error($newContact)) {
1041 if (!CRM_Utils_Array::value('params', $newContact['error_message'])) {
1042 // different kind of error other than DUPLICATE
1043 $errorMessage = $newContact['error_message'];
1044 array_unshift($values, $errorMessage);
1045 $importRecordParams = array(
1046 $statusFieldName => 'ERROR',
1047 "${statusFieldName}Msg" => $errorMessage,
1048 );
1049 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1050 return CRM_Import_Parser::ERROR;
1051 }
1052
1053 $contactID = $newContact['error_message']['params'][0];
1054 if (!in_array($contactID, $this->_newContacts)) {
1055 $this->_newContacts[] = $contactID;
1056 }
1057 }
1058 //CRM-262 No Duplicate Checking
1059 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
1060 array_unshift($values, $url_string);
1061 $importRecordParams = array(
1062 $statusFieldName => 'DUPLICATE',
1063 "${statusFieldName}Msg" => "Skipping duplicate record",
1064 );
1065 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1066 return CRM_Import_Parser::DUPLICATE;
1067 }
1068
1069 $importRecordParams = array(
1070 $statusFieldName => 'IMPORTED',
1071 );
1072 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1073 //return warning if street address is not parsed, CRM-5886
1074 return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
1075 }
1076 else {
1077 // Not a dupe, so we had an error
1078 $errorMessage = $newContact['error_message'];
1079 array_unshift($values, $errorMessage);
1080 $importRecordParams = array(
1081 $statusFieldName => 'ERROR',
1082 "${statusFieldName}Msg" => $errorMessage,
1083 );
1084 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1085 return CRM_Import_Parser::ERROR;
1086 }
1087 }
1088 // sleep(3);
1089 return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID);
1090 }
1091
1092 /**
1093 * Get the array of successfully imported contact id's
1094 *
1095 * @return array
1096 * @access public
1097 */
1098 function &getImportedContacts() {
1099 return $this->_newContacts;
1100 }
1101
1102 /**
1103 * Get the array of successfully imported related contact id's
1104 *
1105 * @return array
1106 * @access public
1107 */
1108 function &getRelatedImportedContacts() {
1109 return $this->_newRelatedContacts;
1110 }
1111
1112 /**
1113 * the initializer code, called before the processing
1114 *
1115 * @return void
1116 * @access public
1117 */
1118 function fini() {}
1119
1120 /**
1121 * function to check if an error in custom data
1122 *
1123 * @param String $errorMessage A string containing all the error-fields.
1124 *
1125 * @access public
1126 */
1127 static function isErrorInCustomData($params, &$errorMessage, $csType = NULL, $relationships = NULL) {
1128 $session = CRM_Core_Session::singleton();
1129 $dateType = $session->get("dateTypes");
1130
1131 if (CRM_Utils_Array::value('contact_sub_type', $params)) {
1132 $csType = CRM_Utils_Array::value('contact_sub_type', $params);
1133 }
1134
1135 if (!CRM_Utils_Array::value('contact_type', $params)) {
1136 $params['contact_type'] = 'Individual';
1137 }
1138 $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, FALSE, $csType);
1139
1140 $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address');
1141 $customFields = $customFields + $addressCustomFields;
1142 foreach ($params as $key => $value) {
1143 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
1144 /* check if it's a valid custom field id */
1145
1146 if (!array_key_exists($customFieldID, $customFields)) {
1147 self::addToErrorMsg(ts('field ID'), $errorMessage);
1148 }
1149 // validate null values for required custom fields of type boolean
1150 if (!empty($customFields[$customFieldID]['is_required']) && (empty($params['custom_'.$customFieldID]) && !is_numeric($params['custom_'.$customFieldID])) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
1151 self::addToErrorMsg($customFields[$customFieldID]['label'].'::'.$customFields[$customFieldID]['groupTitle'], $errorMessage);
1152 }
1153
1154 //For address custom fields, we do get actual custom field value as an inner array of
1155 //values so need to modify
1156 if (array_key_exists($customFieldID, $addressCustomFields)) {
1157 $value = $value[0][$key];
1158 }
1159 /* validate the data against the CF type */
1160
1161 if ($value) {
1162 if ($customFields[$customFieldID]['data_type'] == 'Date') {
1163 if (array_key_exists($customFieldID, $addressCustomFields) && CRM_Utils_Date::convertToDefaultDate($params[$key][0], $dateType, $key)) {
1164 $value = $params[$key][0][$key];
1165 }
1166 else if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
1167 $value = $params[$key];
1168 }
1169 else {
1170 self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1171 }
1172 }
1173 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
1174 if (CRM_Utils_String::strtoboolstr($value) === FALSE) {
1175 self::addToErrorMsg($customFields[$customFieldID]['label'].'::'.$customFields[$customFieldID]['groupTitle'], $errorMessage);
1176 }
1177 }
1178 // need not check for label filed import
1179 $htmlType = array(
1180 'CheckBox',
1181 'Multi-Select',
1182 'AdvMulti-Select',
1183 'Select',
1184 'Radio',
1185 'Multi-Select State/Province',
1186 'Multi-Select Country',
1187 );
1188 if (!in_array($customFields[$customFieldID]['html_type'], $htmlType) || $customFields[$customFieldID]['data_type'] == 'Boolean' || $customFields[$customFieldID]['data_type'] == 'ContactReference') {
1189 $valid = CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $value);
1190 if (!$valid) {
1191 self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1192 }
1193 }
1194
1195 // check for values for custom fields for checkboxes and multiselect
1196 if ($customFields[$customFieldID]['html_type'] == 'CheckBox' || $customFields[$customFieldID]['html_type'] == 'AdvMulti-Select' || $customFields[$customFieldID]['html_type'] == 'Multi-Select') {
1197 $value = trim($value);
1198 $value = str_replace('|', ',', $value);
1199 $mulValues = explode(',', $value);
1200 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1201 foreach ($mulValues as $v1) {
1202 if (strlen($v1) == 0) {
1203 continue;
1204 }
1205
1206 $flag = FALSE;
1207 foreach ($customOption as $v2) {
1208 if ((strtolower(trim($v2['label'])) == strtolower(trim($v1))) || (strtolower(trim($v2['value'])) == strtolower(trim($v1)))) {
1209 $flag = TRUE;
1210 }
1211 }
1212
1213 if (!$flag) {
1214 self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1215 }
1216 }
1217 }
1218 elseif ($customFields[$customFieldID]['html_type'] == 'Select' || ($customFields[$customFieldID]['html_type'] == 'Radio' && $customFields[$customFieldID]['data_type'] != 'Boolean')) {
1219 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1220 $flag = FALSE;
1221 foreach ($customOption as $v2) {
1222 if ((strtolower(trim($v2['label'])) == strtolower(trim($value))) || (strtolower(trim($v2['value'])) == strtolower(trim($value)))) {
1223 $flag = TRUE;
1224 }
1225 }
1226 if (!$flag) {
1227 self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1228 }
1229 }
1230 elseif ($customFields[$customFieldID]['html_type'] == 'Multi-Select State/Province') {
1231 $mulValues = explode(',', $value);
1232 foreach ($mulValues as $stateValue) {
1233 if ($stateValue) {
1234 if (self::in_value(trim($stateValue), CRM_Core_PseudoConstant::stateProvinceAbbreviation()) || self::in_value(trim($stateValue), CRM_Core_PseudoConstant::stateProvince())) {
1235 continue;
1236 }
1237 else {
1238 self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1239 }
1240 }
1241 }
1242 }
1243 elseif ($customFields[$customFieldID]['html_type'] == 'Multi-Select Country') {
1244 $mulValues = explode(',', $value);
1245 foreach ($mulValues as $countryValue) {
1246 if ($countryValue) {
1247 CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
1248 CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
1249 $config = CRM_Core_Config::singleton();
1250 $limitCodes = $config->countryLimit();
1251
1252 $error = TRUE;
1253 foreach (array(
1254 $countryNames,
1255 $countryIsoCodes,
1256 $limitCodes,
1257 ) as $values) {
1258 if (in_array(trim($countryValue), $values)) {
1259 $error = FALSE;
1260 break;
1261 }
1262 }
1263
1264 if ($error) {
1265 self::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1266 }
1267 }
1268 }
1269 }
1270 }
1271 }
1272 elseif (is_array($params[$key]) && isset($params[$key]["contact_type"])) {
1273 //CRM-5125
1274 //supporting custom data of related contact subtypes
1275 $relation = NULL;
1276 if ($relationships) {
1277 if (array_key_exists($key, $relationships)) {
1278 $relation = $key;
1279 }
1280 elseif (CRM_Utils_Array::key($key, $relationships)) {
1281 $relation = CRM_Utils_Array::key($key, $relationships);
1282 }
1283 }
1284 if (!empty($relation)) {
1285 list($id, $first, $second) = CRM_Utils_System::explode('_', $relation, 3);
1286 $direction = "contact_sub_type_$second";
1287 $relationshipType = new CRM_Contact_BAO_RelationshipType();
1288 $relationshipType->id = $id;
1289 if ($relationshipType->find(TRUE)) {
1290 if (isset($relationshipType->$direction)) {
1291 $params[$key]['contact_sub_type'] = $relationshipType->$direction;
1292 }
1293 }
1294 $relationshipType->free();
1295 }
1296
1297 self::isErrorInCustomData($params[$key], $errorMessage, $csType, $relationships);
1298 }
1299 }
1300 }
1301
1302 /**
1303 * Check if value present in all genders or
1304 * as a substring of any gender value, if yes than return corresponding gender.
1305 * eg value might be m/M, ma/MA, mal/MAL, male return 'Male'
1306 * but if value is 'maleabc' than return false
1307 *
1308 * @param string $gender check this value across gender values.
1309 *
1310 * retunr gender value / false
1311 * @access public
1312 */
1313 public function checkGender($gender) {
1314 $gender = trim($gender, '.');
1315 if (!$gender) {
1316 return FALSE;
1317 }
1318
1319 $allGenders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
1320 foreach ($allGenders as $key => $value) {
1321 if (strlen($gender) > strlen($value)) {
1322 continue;
1323 }
1324 if ($gender == $value) {
1325 return $value;
1326 }
1327 if (substr_compare($value, $gender, 0, strlen($gender), TRUE) === 0) {
1328 return $value;
1329 }
1330 }
1331
1332 return FALSE;
1333 }
1334
1335 /**
1336 * function to check if an error in Core( non-custom fields ) field
1337 *
1338 * @param String $errorMessage A string containing all the error-fields.
1339 *
1340 * @access public
1341 */
1342 function isErrorInCoreData($params, &$errorMessage) {
1343 foreach ($params as $key => $value) {
1344 if ($value) {
1345 $session = CRM_Core_Session::singleton();
1346 $dateType = $session->get("dateTypes");
1347
1348 switch ($key) {
1349 case 'birth_date':
1350 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
1351 if (!CRM_Utils_Rule::date($params[$key])) {
1352 self::addToErrorMsg(ts('Birth Date'), $errorMessage);
1353 }
1354 }
1355 else {
1356 self::addToErrorMsg(ts('Birth-Date'), $errorMessage);
1357 }
1358 break;
1359
1360 case 'deceased_date':
1361 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
1362 if (!CRM_Utils_Rule::date($params[$key])) {
1363 self::addToErrorMsg(ts('Deceased Date'), $errorMessage);
1364 }
1365 }
1366 else {
1367 self::addToErrorMsg(ts('Deceased Date'), $errorMessage);
1368 }
1369 break;
1370
1371 case 'is_deceased':
1372 if (CRM_Utils_String::strtoboolstr($value) === FALSE) {
1373 self::addToErrorMsg(ts('Is Deceased'), $errorMessage);
1374 }
1375 break;
1376
1377 case 'gender':
1378 case 'gender_id':
1379 if (!self::checkGender($value)) {
1380 self::addToErrorMsg(ts('Gender'), $errorMessage);
1381 }
1382 break;
1383
1384 case 'preferred_communication_method':
1385 $preffComm = array();
1386 $preffComm = explode(',', $value);
1387 foreach ($preffComm as $v) {
1388 if (!self::in_value(trim($v), CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'))) {
1389 self::addToErrorMsg(ts('Preferred Communication Method'), $errorMessage);
1390 }
1391 }
1392 break;
1393
1394 case 'preferred_mail_format':
1395 if (!array_key_exists(strtolower($value), array_change_key_case(CRM_Core_SelectValues::pmf(), CASE_LOWER))) {
1396 self::addToErrorMsg(ts('Preferred Mail Format'), $errorMessage);
1397 }
1398 break;
1399
1400 case 'individual_prefix':
1401 case 'prefix_id':
1402 if (!self::in_value($value, CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'))) {
1403 self::addToErrorMsg(ts('Individual Prefix'), $errorMessage);
1404 }
1405 break;
1406
1407 case 'individual_suffix':
1408 case 'suffix_id':
1409 if (!self::in_value($value, CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'))) {
1410 self::addToErrorMsg(ts('Individual Suffix'), $errorMessage);
1411 }
1412 break;
1413
1414 case 'state_province':
1415 if (!empty($value)) {
1416 foreach ($value as $stateValue) {
1417 if ($stateValue['state_province']) {
1418 if (self::in_value($stateValue['state_province'], CRM_Core_PseudoConstant::stateProvinceAbbreviation()) ||
1419 self::in_value($stateValue['state_province'], CRM_Core_PseudoConstant::stateProvince())) {
1420 continue;
1421 }
1422 else {
1423 self::addToErrorMsg(ts('State / Province'), $errorMessage);
1424 }
1425 }
1426 }
1427 }
1428 break;
1429
1430 case 'country':
1431 if (!empty($value)) {
1432 foreach ($value as $stateValue) {
1433 if ($stateValue['country']) {
1434 CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
1435 CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
1436 $config = CRM_Core_Config::singleton();
1437 $limitCodes = $config->countryLimit();
1438 //If no country is selected in
1439 //localization then take all countries
1440 if (empty($limitCodes)) {
1441 $limitCodes = $countryIsoCodes;
1442 }
1443
1444 if (self::in_value($stateValue['country'], $limitCodes) || self::in_value($stateValue['country'], CRM_Core_PseudoConstant::country())) {
1445 continue;
1446 }
1447 else {
1448 if (self::in_value($stateValue['country'], $countryIsoCodes) || self::in_value($stateValue['country'], $countryNames)) {
1449 self::addToErrorMsg(ts('Country input value is in table but not "available": "This Country is valid but is NOT in the list of Available Countries currently configured for your site. This can be viewed and modifed from Administer > Localization > Languages, Currency, Locations." '), $errorMessage);
1450 }
1451 else {
1452 self::addToErrorMsg(ts('Country input value not in country table: "The Country value appears to be invalid. It does not match any value in CiviCRM table of countries."'), $errorMessage);
1453 }
1454 }
1455 }
1456 }
1457 }
1458 break;
1459
1460 case 'county':
1461 if (!empty($value)) {
1462 foreach ($value as $county) {
1463 if ($county['county']) {
1464 $countyNames = CRM_Core_PseudoConstant::county();
1465 if (!empty($county['county']) && !in_array($county['county'], $countyNames)) {
1466 self::addToErrorMsg(ts('County input value not in county table: The County value appears to be invalid. It does not match any value in CiviCRM table of counties.'), $errorMessage);
1467 }
1468 }
1469 }
1470 }
1471 break;
1472
1473 case 'geo_code_1':
1474 if (!empty($value)) {
1475 foreach ($value as $codeValue) {
1476 if (CRM_Utils_Array::value('geo_code_1', $codeValue)) {
1477 if (CRM_Utils_Rule::numeric($codeValue['geo_code_1'])) {
1478 continue;
1479 }
1480 else {
1481 self::addToErrorMsg(ts('Geo code 1'), $errorMessage);
1482 }
1483 }
1484 }
1485 }
1486 break;
1487
1488 case 'geo_code_2':
1489 if (!empty($value)) {
1490 foreach ($value as $codeValue) {
1491 if (CRM_Utils_Array::value('geo_code_2', $codeValue)) {
1492 if (CRM_Utils_Rule::numeric($codeValue['geo_code_2'])) {
1493 continue;
1494 }
1495 else {
1496 self::addToErrorMsg(ts('Geo code 2'), $errorMessage);
1497 }
1498 }
1499 }
1500 }
1501 break;
1502 //check for any error in email/postal greeting, addressee,
1503 //custom email/postal greeting, custom addressee, CRM-4575
1504
1505 case 'email_greeting':
1506 $emailGreetingFilter = array(
1507 'contact_type' => $this->_contactType,
1508 'greeting_type' => 'email_greeting',
1509 );
1510 if (!self::in_value($value, CRM_Core_PseudoConstant::greeting($emailGreetingFilter))) {
1511 self::addToErrorMsg(ts('Email Greeting must be one of the configured format options. Check Administer >> System Settings >> Option Groups >> Email Greetings for valid values'), $errorMessage);
1512 }
1513 break;
1514
1515 case 'postal_greeting':
1516 $postalGreetingFilter = array(
1517 'contact_type' => $this->_contactType,
1518 'greeting_type' => 'postal_greeting',
1519 );
1520 if (!self::in_value($value, CRM_Core_PseudoConstant::greeting($postalGreetingFilter))) {
1521 self::addToErrorMsg(ts('Postal Greeting must be one of the configured format options. Check Administer >> System Settings >> Option Groups >> Postal Greetings for valid values'), $errorMessage);
1522 }
1523 break;
1524
1525 case 'addressee':
1526 $addresseeFilter = array(
1527 'contact_type' => $this->_contactType,
1528 'greeting_type' => 'addressee',
1529 );
1530 if (!self::in_value($value, CRM_Core_PseudoConstant::greeting($addresseeFilter))) {
1531 self::addToErrorMsg(ts('Addressee must be one of the configured format options. Check Administer >> System Settings >> Option Groups >> Addressee for valid values'), $errorMessage);
1532 }
1533 break;
1534
1535 case 'email_greeting_custom':
1536 if (array_key_exists('email_greeting', $params)) {
1537 $emailGreetingLabel = key(CRM_Core_OptionGroup::values('email_greeting', TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1538 if (CRM_Utils_Array::value('email_greeting', $params) != $emailGreetingLabel) {
1539 self::addToErrorMsg(ts('Email Greeting - Custom'), $errorMessage);
1540 }
1541 }
1542 break;
1543
1544 case 'postal_greeting_custom':
1545 if (array_key_exists('postal_greeting', $params)) {
1546 $postalGreetingLabel = key(CRM_Core_OptionGroup::values('postal_greeting', TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1547 if (CRM_Utils_Array::value('postal_greeting', $params) != $postalGreetingLabel) {
1548 self::addToErrorMsg(ts('Postal Greeting - Custom'), $errorMessage);
1549 }
1550 }
1551 break;
1552
1553 case 'addressee_custom':
1554 if (array_key_exists('addressee', $params)) {
1555 $addresseeLabel = key(CRM_Core_OptionGroup::values('addressee', TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1556 if (CRM_Utils_Array::value('addressee', $params) != $addresseeLabel) {
1557 self::addToErrorMsg(ts('Addressee - Custom'), $errorMessage);
1558 }
1559 }
1560 break;
1561
1562 case 'url':
1563 if (is_array($value)) {
1564 foreach ($value as $values) {
1565 if (CRM_Utils_Array::value('url', $values) && !CRM_Utils_Rule::url($values['url'])) {
1566 self::addToErrorMsg(ts('Website'), $errorMessage);
1567 break;
1568 }
1569 }
1570 }
1571 break;
1572
1573 case 'do_not_email':
1574 case 'do_not_phone':
1575 case 'do_not_mail':
1576 case 'do_not_sms':
1577 case 'do_not_trade':
1578 if (CRM_Utils_Rule::boolean($value) == FALSE) {
1579 $key = ucwords(str_replace("_", " ", $key));
1580 self::addToErrorMsg($key, $errorMessage);
1581 }
1582 break;
1583
1584 case 'email':
1585 if (is_array($value)) {
1586 foreach ($value as $values) {
1587 if (CRM_Utils_Array::value('email', $values) && !CRM_Utils_Rule::email($values['email'])) {
1588 self::addToErrorMsg($key, $errorMessage);
1589 break;
1590 }
1591 }
1592 }
1593 break;
1594
1595 default:
1596 if (is_array($params[$key]) && isset($params[$key]["contact_type"])) {
1597 //check for any relationship data ,FIX ME
1598 self::isErrorInCoreData($params[$key], $errorMessage);
1599 }
1600 }
1601 }
1602 }
1603 }
1604
1605 /**
1606 * function to ckeck a value present or not in a array
1607 *
1608 * @return ture if value present in array or retun false
1609 *
1610 * @access public
1611 */
1612 function in_value($value, $valueArray) {
1613 foreach ($valueArray as $key => $v) {
1614 //fix for CRM-1514
1615 if (strtolower(trim($v, ".")) == strtolower(trim($value, "."))) {
1616 return TRUE;
1617 }
1618 }
1619 return FALSE;
1620 }
1621
1622 /**
1623 * function to build error-message containing error-fields
1624 *
1625 * @param String $errorName A string containing error-field name.
1626 * @param String $errorMessage A string containing all the error-fields, where the new errorName is concatenated.
1627 *
1628 * @static
1629 * @access public
1630 */
1631 static function addToErrorMsg($errorName, &$errorMessage) {
1632 if ($errorMessage) {
1633 $errorMessage .= "; $errorName";
1634 }
1635 else {
1636 $errorMessage = $errorName;
1637 }
1638 }
1639
1640 /**
1641 * method for creating contact
1642 *
1643 *
1644 */
1645 function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = NULL, $requiredCheck = TRUE, $dedupeRuleGroupID = NULL) {
1646 $dupeCheck = FALSE;
1647
1648 $newContact = NULL;
1649
1650 if (is_null($contactId) && ($onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK)) {
1651 $dupeCheck = (bool)($onDuplicate);
1652 }
1653
1654 //get the prefix id etc if exists
1655 CRM_Contact_BAO_Contact::resolveDefaults($formatted, TRUE);
1656
1657 require_once 'CRM/Utils/DeprecatedUtils.php';
1658 //@todo direct call to API function not supported.
1659 // setting required check to false, CRM-2839
1660 // plus we do our own required check in import
1661 $error = _civicrm_api3_deprecated_contact_check_params($formatted, $dupeCheck, TRUE, FALSE, $dedupeRuleGroupID);
1662
1663 if ((is_null($error)) && (civicrm_error(_civicrm_api3_deprecated_validate_formatted_contact($formatted)))) {
1664 $error = _civicrm_api3_deprecated_validate_formatted_contact($formatted);
1665 }
1666
1667 $newContact = $error;
1668
1669 if (is_null($error)) {
1670 if ($contactId) {
1671 $this->formatParams($formatted, $onDuplicate, (int) $contactId);
1672 }
1673
1674 // pass doNotResetCache flag since resetting and rebuilding cache could be expensive.
1675 $config = CRM_Core_Config::singleton();
1676 $config->doNotResetCache = 1;
1677 $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']);
1678 $config->doNotResetCache = 0;
1679
1680 $contact = array(
1681 'contact_id' => $cid,
1682 );
1683
1684 $defaults = array();
1685 $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults);
1686 }
1687
1688 //get the id of the contact whose street address is not parsable, CRM-5886
1689 if ($this->_parseStreetAddress && is_object($newContact) && property_exists($newContact, 'address') && $newContact->address) {
1690 foreach ($newContact->address as $address) {
1691 if (!empty($address['street_address']) && (!CRM_Utils_Array::value('street_number', $address) || !CRM_Utils_Array::value('street_name', $address))) {
1692 $this->_unparsedStreetAddressContacts[] = array(
1693 'id' => $newContact->id,
1694 'streetAddress' => $address['street_address'],
1695 );
1696 }
1697 }
1698 }
1699 return $newContact;
1700 }
1701
1702 /**
1703 * format params for update and fill mode
1704 *
1705 * @param $params array referance to an array containg all the
1706 * values for import
1707 * @param $onDuplicate int
1708 * @param $cid int contact id
1709 */
1710 function formatParams(&$params, $onDuplicate, $cid) {
1711 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
1712 return;
1713 }
1714
1715 $contactParams = array(
1716 'contact_id' => $cid,
1717 );
1718
1719 $defaults = array();
1720 $contactObj = CRM_Contact_BAO_Contact::retrieve($contactParams, $defaults);
1721
1722 $modeUpdate = $modeFill = FALSE;
1723
1724 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
1725 $modeUpdate = TRUE;
1726 }
1727
1728 if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
1729 $modeFill = TRUE;
1730 }
1731
1732 $groupTree = CRM_Core_BAO_CustomGroup::getTree($params['contact_type'], CRM_Core_DAO::$_nullObject, $cid, 0, NULL);
1733 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults, FALSE, FALSE);
1734
1735 $locationFields = array(
1736 'email' => 'email',
1737 'phone' => 'phone',
1738 'im' => 'name',
1739 'website' => 'website',
1740 'address' => 'address',
1741 );
1742
1743 $contact = get_object_vars($contactObj);
1744
1745 foreach ($params as $key => $value) {
1746 if ($key == 'id' || $key == 'contact_type') {
1747 continue;
1748 }
1749
1750 if (array_key_exists($key, $locationFields)) {
1751 continue;
1752 }
1753 elseif (in_array($key, array(
1754 'email_greeting',
1755 'postal_greeting',
1756 'addressee',
1757 ))) {
1758 // CRM-4575, need to null custom
1759 if ($params["{$key}_id"] != 4) {
1760 $params["{$key}_custom"] = 'null';
1761 }
1762 unset($params[$key]);
1763 }
1764 elseif ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) {
1765 $custom = TRUE;
1766 }
1767 else {
1768 $getValue = CRM_Utils_Array::retrieveValueRecursive($contact, $key);
1769
1770 if ($key == 'contact_source') {
1771 $params['source'] = $params[$key];
1772 unset($params[$key]);
1773 }
1774
1775 if ($modeFill && isset($getValue)) {
1776 unset($params[$key]);
1777 }
1778 }
1779 }
1780
1781 foreach ($locationFields as $locKeys) {
1782 if (is_array(CRM_Utils_Array::value($locKeys, $params))) {
1783 foreach ($params[$locKeys] as $key => $value) {
1784 if ($modeFill) {
1785 $getValue = CRM_Utils_Array::retrieveValueRecursive($contact, $locKeys);
1786
1787 if (isset($getValue)) {
1788 foreach ($getValue as $cnt => $values) {
1789 if ($locKeys == 'website') {
1790 if (($getValue[$cnt]['website_type_id'] == $params[$locKeys][$key]['website_type_id'])) {
1791 unset($params[$locKeys][$key]);
1792 }
1793 }
1794 else {
1795 if ((!empty($getValue[$cnt]['location_type_id']) && !empty($params[$locKeys][$key]['location_type_id'])) && $getValue[$cnt]['location_type_id'] == $params[$locKeys][$key]['location_type_id']) {
1796 unset($params[$locKeys][$key]);
1797 }
1798 }
1799 }
1800 }
1801 }
1802 }
1803 if (count($params[$locKeys]) == 0) {
1804 unset($params[$locKeys]);
1805 }
1806 }
1807 }
1808 }
1809
1810 /**
1811 * convert any given date string to default date array.
1812 *
1813 * @param array $params has given date-format
1814 * @param array $formatted store formatted date in this array
1815 * @param int $dateType type of date
1816 * @param string $dateParam index of params
1817 * @static
1818 */
1819 function formatCustomDate(&$params, &$formatted, $dateType, $dateParam) {
1820 //fix for CRM-2687
1821 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $dateParam);
1822 $formatted[$dateParam] = CRM_Utils_Date::processDate($params[$dateParam]);
1823 }
1824
1825 /**
1826 * format common params data to proper format to store.
1827 *
1828 * @param array $params contain record values.
1829 * @param array $formatted array of formatted data.
1830 * @param array $contactFields contact DAO fields.
1831 * @static
1832 */
1833 function formatCommonData($params, &$formatted, &$contactFields) {
1834 $csType = array(
1835 CRM_Utils_Array::value('contact_type', $formatted),
1836 );
1837
1838 //CRM-5125
1839 //add custom fields for contact sub type
1840 if (!empty($this->_contactSubType)) {
1841 $csType = $this->_contactSubType;
1842 }
1843
1844 if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
1845 $csType = $relCsType;
1846 }
1847
1848 $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], FALSE, FALSE, $csType);
1849
1850 $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address');
1851 $customFields = $customFields + $addressCustomFields;
1852
1853 //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
1854 $elements = array(
1855 'email_greeting_custom' => 'email_greeting',
1856 'postal_greeting_custom' => 'postal_greeting',
1857 'addressee_custom' => 'addressee',
1858 );
1859 foreach ($elements as $k => $v) {
1860 if (array_key_exists($k, $params) && !(array_key_exists($v, $params))) {
1861 $label = key(CRM_Core_OptionGroup::values($v, TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1862 $params[$v] = $label;
1863 }
1864 }
1865
1866 //format date first
1867 $session = CRM_Core_Session::singleton();
1868 $dateType = $session->get("dateTypes");
1869 foreach ($params as $key => $val) {
1870 $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
1871 if ($customFieldID &&
1872 !array_key_exists($customFieldID, $addressCustomFields)) {
1873 //we should not update Date to null, CRM-4062
1874 if ($val && ($customFields[$customFieldID]['data_type'] == 'Date')) {
1875 self::formatCustomDate($params, $formatted, $dateType, $key);
1876 }
1877 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
1878 if (empty($val) && !is_numeric($val) && $this->_onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
1879 //retain earlier value when Import mode is `Fill`
1880 unset($params[$key]);
1881 }
1882 else {
1883 $params[$key] = CRM_Utils_String::strtoboolstr($val);
1884 }
1885 }
1886
1887 if ($key == 'birth_date' && $val) {
1888 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
1889 }
1890 elseif ($key == 'deceased_date' && $val) {
1891 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
1892 }
1893 elseif ($key == 'is_deceased' && $val) {
1894 $params[$key] = CRM_Utils_String::strtoboolstr($val);
1895 }
1896 elseif ($key == 'gender') {
1897 //CRM-4360
1898 $params[$key] = $this->checkGender($val);
1899 }
1900 }
1901 }
1902
1903 //now format custom data.
1904 foreach ($params as $key => $field) {
1905 if (is_array($field)) {
1906 $isAddressCustomField = FALSE;
1907 foreach ($field as $value) {
1908 $break = FALSE;
1909 if (is_array($value)) {
1910 foreach ($value as $name => $testForEmpty) {
1911 if ($addressCustomFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
1912 $isAddressCustomField = TRUE;
1913 break;
1914 }
1915 // check if $value does not contain IM provider or phoneType
1916 if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == NULL)) {
1917 $break = TRUE;
1918 break;
1919 }
1920 }
1921 }
1922 else {
1923 $break = TRUE;
1924 }
1925
1926 if (!$break) {
1927 require_once 'CRM/Utils/DeprecatedUtils.php';
1928 _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
1929 }
1930 }
1931 if (!$isAddressCustomField) {
1932 continue;
1933 }
1934 }
1935
1936 $formatValues = array(
1937 $key => $field,
1938 );
1939
1940 if (($key !== 'preferred_communication_method') && (array_key_exists($key, $contactFields))) {
1941 // due to merging of individual table and
1942 // contact table, we need to avoid
1943 // preferred_communication_method forcefully
1944 $formatValues['contact_type'] = $formatted['contact_type'];
1945 }
1946
1947 if ($key == 'id' && isset($field)) {
1948 $formatted[$key] = $field;
1949 }
1950 require_once 'CRM/Utils/DeprecatedUtils.php';
1951 _civicrm_api3_deprecated_add_formatted_param($formatValues, $formatted);
1952
1953 //Handling Custom Data
1954 // note: Address custom fields will be handled separately inside _civicrm_api3_deprecated_add_formatted_param
1955 if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) &&
1956 array_key_exists($customFieldID, $customFields) &&
1957 !array_key_exists($customFieldID, $addressCustomFields)) {
1958
1959 $extends = CRM_Utils_Array::value('extends', $customFields[$customFieldID]);
1960 $htmlType = CRM_Utils_Array::value( 'html_type', $customFields[$customFieldID] );
1961 switch ( $htmlType ) {
1962 case 'Select':
1963 case 'Radio':
1964 case 'Autocomplete-Select':
1965 if ($customFields[$customFieldID]['data_type'] == 'String') {
1966 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1967 foreach ($customOption as $customFldID => $customValue) {
1968 $val = CRM_Utils_Array::value('value', $customValue);
1969 $label = CRM_Utils_Array::value('label', $customValue);
1970 $label = strtolower($label);
1971 $value = strtolower(trim($formatted[$key]));
1972 if (($value == $label) || ($value == strtolower($val))) {
1973 $params[$key] = $formatted[$key] = $val;
1974 }
1975 }
1976 }
1977 break;
1978 case 'CheckBox':
1979 case 'AdvMulti-Select':
1980 case 'Multi-Select':
1981
1982 if ( CRM_Utils_Array::value( $key, $formatted ) && CRM_Utils_Array::value( $key, $params ) ) {
1983 $mulValues = explode( ',', $formatted[$key] );
1984 $customOption = CRM_Core_BAO_CustomOption::getCustomOption( $customFieldID, true );
1985 $formatted[$key] = array( );
1986 $params[$key] = array( );
1987 foreach ( $mulValues as $v1 ) {
1988 foreach ( $customOption as $v2 ) {
1989 if ( ( strtolower( $v2['label'] ) == strtolower( trim( $v1 ) ) ) ||
1990 ( strtolower( $v2['value'] ) == strtolower( trim( $v1 ) ) ) ) {
1991 if ( $htmlType == 'CheckBox' ) {
1992 $params[$key][$v2['value']] = $formatted[$key][$v2['value']] = 1;
1993 } else {
1994 $params[$key][] = $formatted[$key][] = $v2['value'];
1995 }
1996 }
1997 }
1998 }
1999 }
2000 break;
2001 }
2002 }
2003 }
2004
2005 if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) &&
2006 !array_key_exists($customFieldID, $addressCustomFields)) {
2007 // @todo calling api functions directly is not supported
2008 _civicrm_api3_custom_format_params($params, $formatted, $extends);
2009 }
2010
2011 // to check if not update mode and unset the fields with empty value.
2012 if (!$this->_updateWithId && array_key_exists('custom', $formatted)) {
2013 foreach ($formatted['custom'] as $customKey => $customvalue) {
2014 if (empty($formatted['custom'][$customKey][- 1]['is_required'])) {
2015 $formatted['custom'][$customKey][-1]['is_required'] = $customFields[$customKey]['is_required'];
2016 }
2017 $emptyValue = CRM_Utils_Array::value('value', $customvalue[ - 1]);
2018 if (!isset($emptyValue)) {
2019 unset($formatted['custom'][$customKey]);
2020 }
2021 }
2022 }
2023
2024 // parse street address, CRM-5450
2025 if ($this->_parseStreetAddress) {
2026 if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
2027 foreach ($formatted['address'] as $instance => & $address) {
2028 $streetAddress = CRM_Utils_Array::value('street_address', $address);
2029 if (empty($streetAddress)) {
2030 continue;
2031 }
2032 // parse address field.
2033 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
2034
2035 //street address consider to be parsed properly,
2036 //If we get street_name and street_number.
2037 if (!CRM_Utils_Array::value('street_name', $parsedFields) || !CRM_Utils_Array::value('street_number', $parsedFields)) {
2038 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
2039 }
2040
2041 // merge parse address w/ main address block.
2042 $address = array_merge($address, $parsedFields);
2043 }
2044 }
2045 }
2046 }
2047
2048 /**
2049 * Function to generate status and error message for unparsed street address records.
2050 *
2051 * @param array $values the array of values belonging to each row
2052 * @param array $statusFieldName store formatted date in this array
2053
2054 * @access public
2055 */
2056 function processMessage(&$values, $statusFieldName, $returnCode) {
2057 if (empty($this->_unparsedStreetAddressContacts)) {
2058 $importRecordParams = array(
2059 $statusFieldName => 'IMPORTED',
2060 );
2061 }
2062 else {
2063 $errorMessage = ts("Record imported successfully but unable to parse the street address: ");
2064 foreach ($this->_unparsedStreetAddressContacts as $contactInfo => $contactValue) {
2065 $contactUrl = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contactValue['id'], TRUE, NULL, FALSE);
2066 $errorMessage .= "\n Contact ID:" . $contactValue['id'] . " <a href=\"$contactUrl\"> " . $contactValue['streetAddress'] . "</a>";
2067 }
2068 array_unshift($values, $errorMessage);
2069 $importRecordParams = array(
2070 $statusFieldName => 'ERROR',
2071 "${statusFieldName}Msg" => $errorMessage,
2072 );
2073 $returnCode = CRM_Import_Parser::UNPARSED_ADDRESS_WARNING;
2074 }
2075 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
2076 return $returnCode;
2077 }
2078
2079 function checkRelatedContactFields($relKey, $params) {
2080 //avoid blank contact creation.
2081 $allowToCreate = FALSE;
2082
2083 //build the mapper field array.
2084 static $relatedContactFields = array();
2085 if (!isset($relatedContactFields[$relKey])) {
2086 foreach ($this->_mapperRelated as $key => $name) {
2087 if (!$name) {
2088 continue;
2089 }
2090
2091 if ( CRM_Utils_Array::value($name, $relatedContactFields) && !is_array($relatedContactFields[$name])) {
2092 $relatedContactFields[$name] = array();
2093 }
2094 $fldName = CRM_Utils_Array::value($key, $this->_mapperRelatedContactDetails);
2095 if ($fldName == 'url') {
2096 $fldName = 'website';
2097 }
2098 if ($fldName) {
2099 $relatedContactFields[$name][] = $fldName;
2100 }
2101 }
2102 }
2103
2104 //validate for passed data.
2105 if (is_array($relatedContactFields[$relKey])) {
2106 foreach ($relatedContactFields[$relKey] as $fld) {
2107 if (CRM_Utils_Array::value($fld, $params)) {
2108 $allowToCreate = TRUE;
2109 break;
2110 }
2111 }
2112 }
2113
2114 return $allowToCreate;
2115 }
2116 }
2117