/** * The summary function is a magic & mystical function I have only partially made sense of but note that * it makes a call to setActiveFieldValues - without which import won't work - so it's more than just a presentation * function * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * It is called from both the preview & the import actions * (non-PHP doc) * @see CRM_Csvimport_Import_Parser_BaseClass::summary() */ function summary(&$values) { $erroneousField = NULL; $response = $this->setActiveFieldValues($values, $erroneousField); $errorRequired = FALSE; $missingField = ''; $this->_params =& $this->getActiveFieldParams(); foreach ($this->_requiredFields as $requiredField) { if (empty($this->_params[$requiredField])) { $errorRequired = TRUE; $missingField .= ' ' . $requiredField; CRM_Contact_Import_Parser_Contact::addToErrorMsg($this->_entity, $requiredField); } } if ($errorRequired) { array_unshift($values, ts('Missing required field(s) :') . $missingField); return CRM_Import_Parser::ERROR; } $errorMessage = NULL; //@todo add a validate fn to the apis so that we can dry run against them to check // pseudoconstants if ($errorMessage) { $tempMsg = "Invalid value for field(s) : {$errorMessage}"; array_unshift($values, $tempMsg); $errorMessage = NULL; return CRM_Import_Parser::ERROR; } return CRM_Import_Parser::VALID; }
/** * The summary function is a magic & mystical function * it makes a call to setActiveFieldValues - without which import won't work * function * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * It is called from both the preview & the import actions * (non-PHPdoc) * @see CRM_Hrjobcontract_Import_Parser_BaseClass::summary() */ function summary(&$values) { $erroneousField = NULL; $response = $this->setActiveFieldValues($values, $erroneousField); $errorRequired = FALSE; $missingField = ''; $errorMessage = NULL; $errorMessages = array(); return CRM_Import_Parser::VALID; ///TODO! foreach ($this->_entity as $entity) { $this->_params = $this->getActiveFieldParams(); foreach ($this->_requiredFields as $requiredFieldKey => $requiredFieldVal) { // TODO: code below is TEMPORARY! if ($requiredFieldVal === 'jobcontract_id') { continue; } if (empty($this->_params[$requiredFieldVal])) { $errorRequired = TRUE; $missingField .= ' ' . $requiredFieldVal; //// TODO: BUG? previously: $requiredField; CRM_Contact_Import_Parser_Contact::addToErrorMsg($entity, $requiredFieldVal); } } //checking error in core data $this->isErrorInCoreData($this->_params, $errorMessage); if ($errorMessage) { $errorMessages[] = $errorMessage; $tempMsg = "Invalid value for field(s) : {$errorMessage}"; CRM_Contact_Import_Parser_Contact::addToErrorMsg($entity, $errorMessage); } } if ($errorRequired) { array_unshift($values, ts('Missing required field(s) :') . $missingField); return CRM_Import_Parser::ERROR; } if ($errorMessage) { $tempMsg = "Invalid value for field(s) : {$errorMessage}"; array_unshift($values, $tempMsg); $errorMessage = NULL; return CRM_Import_Parser::ERROR; } return CRM_Import_Parser::VALID; }
/** * handle the values in import mode * * @param int $onDuplicate the code for what action to take on duplicates * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function import($onDuplicate, &$values) { try { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); //assign join date equal to start date if join date is not provided if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) { $params['join_date'] = $params['membership_start_date']; } $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $formatted = array(); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date')); foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'join_date': case 'membership_start_date': case 'membership_end_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage); } } else { CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage); } break; case 'membership_type_id': if (!is_numeric($val)) { unset($params['membership_type_id']); $params['membership_type'] = $val; } break; case 'status_id': if (!is_numeric($val)) { unset($params['status_id']); $params['membership_status'] = $val; } break; case 'is_override': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $tempIndieFields = CRM_Member_DAO_Membership::import(); $indieFields = $tempIndieFields; } $formatValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $formatValues[$key] = $field; } //format params to meet api v2 requirements. //@todo find a way to test removing this formatting $formatError = $this->membership_format_params($formatValues, $formatted, TRUE); if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership'); } else { //fix for CRM-2219 Update Membership // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) { array_unshift($values, 'Required parameter missing: Status'); return CRM_Import_Parser::ERROR; } if (!empty($formatValues['membership_id'])) { $dao = new CRM_Member_BAO_Membership(); $dao->id = $formatValues['membership_id']; $dates = array('join_date', 'start_date', 'end_date'); foreach ($dates as $v) { if (!CRM_Utils_Array::value($v, $formatted)) { $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v); } } $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership'); if ($dao->find(TRUE)) { $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID')); $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } else { $this->_newMemberships[] = $newMembership->id; return CRM_Import_Parser::VALID; } } else { array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } //Format dates $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d'); $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d'); $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d'); if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $formatValues['version'] = 3; require_once 'CRM/Utils/DeprecatedUtils.php'; $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; //fix for CRM-1924 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = FALSE; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted); if (!CRM_Utils_Array::value('status_id', $formatted)) { $formatted['status_id'] = $calcStatus['id']; } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.'); return CRM_Import_Parser::ERROR; } elseif ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.'); return CRM_Import_Parser::ERROR; } } $newMembership = civicrm_api3('membership', 'create', $formatted); $this->_newMemberships[] = $newMembership['id']; return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = ''; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (CRM_Utils_Array::value('external_identifier', $params)) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (CRM_Utils_Array::value('external_identifier', $formatValues)) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } //to calculate dates $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //end of date calculation part //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = FALSE; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted); if (!CRM_Utils_Array::value('status_id', $formatted)) { $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus); } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.'); return CRM_Import_Parser::ERROR; } elseif ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.'); return CRM_Import_Parser::ERROR; } } $newMembership = civicrm_api3('membership', 'create', $formatted); $this->_newMemberships[] = $newMembership['id']; return CRM_Import_Parser::VALID; } } catch (Exception $e) { array_unshift($values, $e->getMessage()); return CRM_Import_Parser::ERROR; } }
/** * Call the DataSource's postProcess method to take over * and then setup some common data structures for the next step * * @return void * @access public */ public function postProcess() { $this->controller->resetPage('MapField'); if ($this->_dataSourceIsValid) { // Setup the params array $this->_params = $this->controller->exportValues($this->_name); $storeParams = array('onDuplicate' => 'onDuplicate', 'dedupe' => 'dedupe', 'contactType' => 'contactType', 'contactSubType' => 'subType', 'dateFormats' => 'dateFormats', 'savedMapping' => 'savedMapping'); foreach ($storeParams as $storeName => $storeValueName) { ${$storeName} = $this->exportValue($storeValueName); $this->set($storeName, ${$storeName}); } $this->set('dataSource', $this->_params['dataSource']); $this->set('skipColumnHeader', CRM_Utils_Array::value('skipColumnHeader', $this->_params)); $session = CRM_Core_Session::singleton(); $session->set('dateTypes', $dateFormats); // Get the PEAR::DB object $dao = new CRM_Core_DAO(); $db = $dao->getDatabaseConnection(); //hack to prevent multiple tables. $this->_params['import_table_name'] = $this->get('importTableName'); if (!$this->_params['import_table_name']) { $this->_params['import_table_name'] = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE)); } $this->_dataSourceClass->postProcess($this->_params, $db, $this); // We should have the data in the DB now, parse it $importTableName = $this->get('importTableName'); $fieldNames = $this->_prepareImportTable($db, $importTableName); $mapper = array(); $parser = new CRM_Contact_Import_Parser_Contact($mapper); $parser->setMaxLinesToProcess(100); $parser->run($importTableName, $mapper, CRM_Import_Parser::MODE_MAPFIELD, $contactType, $fieldNames['pk'], $fieldNames['status'], CRM_Import_Parser::DUPLICATE_SKIP, NULL, NULL, FALSE, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $contactSubType, $dedupe); // add all the necessary variables to the form $parser->set($this); } else { CRM_Core_Error::fatal("Invalid DataSource on form post. This shouldn't happen!"); } }
/** * Process the mapped fields and map it into the uploaded file * preview the file and extract some summary statistics * * @return void * @access public */ public function postProcessOld() { $doGeocodeAddress = $this->controller->exportValue('DataSource', 'doGeocodeAddress'); $invalidRowCount = $this->get('invalidRowCount'); $conflictRowCount = $this->get('conflictRowCount'); $onDuplicate = $this->get('onDuplicate'); $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName'); $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc'); $groups = $this->controller->exportValue($this->_name, 'groups'); $allGroups = $this->get('groups'); $newTagName = $this->controller->exportValue($this->_name, 'newTagName'); $newTagDesc = $this->controller->exportValue($this->_name, 'newTagDesc'); $tag = $this->controller->exportValue($this->_name, 'tag'); $allTags = $this->get('tag'); $mapper = $this->controller->exportValue('MapField', 'mapper'); $mapperKeys = array(); $mapperLocTypes = array(); $mapperPhoneTypes = array(); $mapperRelated = array(); $mapperRelatedContactType = array(); $mapperRelatedContactDetails = array(); $mapperRelatedContactLocType = array(); $mapperRelatedContactPhoneType = array(); foreach ($mapper as $key => $value) { $mapperKeys[$key] = $mapper[$key][0]; if (is_numeric($mapper[$key][1])) { $mapperLocTypes[$key] = $mapper[$key][1]; } else { $mapperLocTypes[$key] = NULL; } if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') { $mapperPhoneTypes[$key] = $mapper[$key][2]; } else { $mapperPhoneTypes[$key] = NULL; } list($id, $first, $second) = explode('_', $mapper[$key][0]); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $fieldName = "contact_type_{$second}"; $mapperRelatedContactType[$key] = $relationType->{$fieldName}; $mapperRelated[$key] = $mapper[$key][0]; $mapperRelatedContactDetails[$key] = $mapper[$key][1]; $mapperRelatedContactLocType[$key] = $mapper[$key][2]; $mapperRelatedContactPhoneType[$key] = $mapper[$key][3]; } else { $mapperRelated[$key] = NULL; $mapperRelatedContactType[$key] = NULL; $mapperRelatedContactDetails[$key] = NULL; $mapperRelatedContactLocType[$key] = NULL; $mapperRelatedContactPhoneType[$key] = NULL; } } $parser = new CRM_Contact_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType); $mapFields = $this->get('fields'); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); foreach ($mapper as $key => $value) { $header = array(); list($id, $first, $second) = explode('_', $mapper[$key][0]); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $header[] = $relationType->name_a_b; $header[] = ucwords(str_replace("_", " ", $mapper[$key][1])); if (isset($mapper[$key][2])) { $header[] = $locationTypes[$mapper[$key][2]]; } if (isset($mapper[$key][3])) { $header[] = $phoneTypes[$mapper[$key][3]]; } } else { if (isset($mapFields[$mapper[$key][0]])) { $header[] = $mapFields[$mapper[$key][0]]; if (isset($mapper[$key][1])) { $header[] = $locationTypes[$mapper[$key][1]]; } if (isset($mapper[$key][2])) { $header[] = $phoneTypes[$mapper[$key][2]]; } } } $mapperFields[] = implode(' - ', $header); } $tableName = $this->get('importTableName'); //print "Running parser on table: $tableName<br/>"; $parser->run($tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->get('contactType'), $this->get('primaryKeyName'), $this->get('statusFieldName'), $onDuplicate, $this->get('statusID'), $this->get('totalRowCount'), $doGeocodeAddress, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'), $this->get('dedupe')); // add the new contacts to selected groups $contactIds =& $parser->getImportedContacts(); // add the new related contacts to selected groups $relatedContactIds =& $parser->getRelatedImportedContacts(); $this->set('relatedCount', count($relatedContactIds)); $newGroupId = NULL; //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {" if ($newGroupName) { /* Create a new group */ $gParams = array('name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE); $group = CRM_Contact_BAO_Group::create($gParams); $groups[] = $newGroupId = $group->id; } if (is_array($groups)) { $groupAdditions = array(); foreach ($groups as $groupId) { $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId); if (!empty($relatedContactIds)) { $addRelCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId); } $totalCount = $addCount[1] + $addRelCount[1]; if ($groupId == $newGroupId) { $name = $newGroupName; $new = TRUE; } else { $name = $allGroups[$groupId]; $new = FALSE; } $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2] + $addRelCount[2], 'new' => $new); } $this->set('groupAdditions', $groupAdditions); } $newTagId = NULL; if ($newTagName) { /* Create a new Tag */ $tagParams = array('name' => $newTagName, 'title' => $newTagName, 'description' => $newTagDesc, 'is_active' => TRUE); $id = array(); $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id); $tag[$addedTag->id] = 1; } //add Tag to Import if (is_array($tag)) { $tagAdditions = array(); foreach ($tag as $tagId => $val) { $addTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId); if (!empty($relatedContactIds)) { $addRelTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($relatedContactIds, $tagId); } $totalTagCount = $addTagCount[1] + $addRelTagCount[1]; if ($tagId == $addedTag->id) { $tagName = $newTagName; $new = TRUE; } else { $tagName = $allTags[$tagId]; $new = FALSE; } $tagAdditions[] = array('url' => CRM_Utils_System::url('civicrm/contact/search', 'reset=1&force=1&context=smog&id=' . $tagId), 'name' => $tagName, 'added' => $totalTagCount, 'notAdded' => $addTagCount[2] + $addRelTagCount[2], 'new' => $new); } $this->set('tagAdditions', $tagAdditions); } // add all the necessary variables to the form $parser->set($this, CRM_Import_Parser::MODE_IMPORT); // check if there is any error occured $errorStack = CRM_Core_Error::singleton(); $errors = $errorStack->getErrors(); $errorMessage = array(); if (is_array($errors)) { foreach ($errors as $key => $value) { $errorMessage[] = $value['message']; } // there is no fileName since this is a sql import // so fudge it $config = CRM_Core_Config::singleton(); $errorFile = $config->uploadDir . "sqlImport.error.log"; if ($fd = fopen($errorFile, 'w')) { fwrite($fd, implode('\\n', $errorMessage)); } fclose($fd); $this->set('errorFile', $errorFile); $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser'; $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlparams)); $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser'; $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams)); $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser'; $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams)); } }
/** * Process the mapped fields and map it into the uploaded file. */ public function postProcess() { $params = $this->controller->exportValues('MapField'); //reload the mapfield if load mapping is pressed if (!empty($params['savedMapping'])) { $this->set('savedMapping', $params['savedMapping']); $this->controller->resetPage($this->_name); return; } $mapper = array(); $mapperKeys = array(); $mapperKeys = $this->controller->exportValue($this->_name, 'mapper'); $mapperKeysMain = array(); $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); //these mapper params need to set key as array and val as null. $mapperParams = array('related' => 'relatedVal', 'locations' => 'locationsVal', 'mapperLocType' => 'mapperLocTypeVal', 'mapperPhoneType' => 'mapperPhoneTypeVal', 'mapperImProvider' => 'mapperImProviderVal', 'mapperWebsiteType' => 'mapperWebsiteTypeVal', 'relatedContactType' => 'relatedContactTypeVal', 'relatedContactDetails' => 'relatedContactDetailsVal', 'relatedContactLocType' => 'relatedContactLocTypeVal', 'relatedContactPhoneType' => 'relatedContactPhoneTypeVal', 'relatedContactImProvider' => 'relatedContactImProviderVal', 'relatedContactWebsiteType' => 'relatedContactWebsiteTypeVal'); //set respective mapper params to array. foreach (array_keys($mapperParams) as $mapperParam) { ${$mapperParam} = array(); } for ($i = 0; $i < $this->_columnCount; $i++) { //set respective mapper value to null foreach (array_values($mapperParams) as $mapperParam) { ${$mapperParam} = NULL; } $fldName = CRM_Utils_Array::value(0, $mapperKeys[$i]); $selOne = CRM_Utils_Array::value(1, $mapperKeys[$i]); $selTwo = CRM_Utils_Array::value(2, $mapperKeys[$i]); $selThree = CRM_Utils_Array::value(3, $mapperKeys[$i]); $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]]; $mapperKeysMain[$i] = $fldName; //need to differentiate non location elements. if ($selOne && is_numeric($selOne)) { if ($fldName == 'url') { $mapperWebsiteTypeVal = $websiteTypes[$selOne]; } else { $locationsVal = $locationTypes[$selOne]; $mapperLocTypeVal = $selOne; if ($selTwo && is_numeric($selTwo)) { if ($fldName == 'phone') { $mapperPhoneTypeVal = $phoneTypes[$selTwo]; } elseif ($fldName == 'im') { $mapperImProviderVal = $imProviders[$selTwo]; } } } } //relationship contact mapper info. list($id, $first, $second) = CRM_Utils_System::explode('_', $fldName, 3); if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $relatedVal = $this->_mapperFields[$fldName]; if ($selOne) { if ($selOne == 'url') { $relatedContactWebsiteTypeVal = $websiteTypes[$selTwo]; } else { $relatedContactLocTypeVal = CRM_Utils_Array::value($selTwo, $locationTypes); if ($selThree) { if ($selOne == 'phone') { $relatedContactPhoneTypeVal = $phoneTypes[$selThree]; } elseif ($selOne == 'im') { $relatedContactImProviderVal = $imProviders[$selThree]; } } } //get the related contact type. $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $relatedContactTypeVal = $relationType->{"contact_type_{$second}"}; $relatedContactDetailsVal = $this->_formattedFieldNames[$relatedContactTypeVal][$selOne]; } } //set the respective mapper param array values. foreach ($mapperParams as $mapperParamKey => $mapperParamVal) { ${$mapperParamKey}[$i] = ${$mapperParamVal}; } } $this->set('columnNames', $this->_columnNames); //set main contact properties. $properties = array('ims' => 'mapperImProvider', 'mapper' => 'mapper', 'phones' => 'mapperPhoneType', 'websites' => 'mapperWebsiteType', 'locations' => 'locations'); foreach ($properties as $propertyName => $propertyVal) { $this->set($propertyName, ${$propertyVal}); } //set related contact propeties. $relProperties = array('related', 'relatedContactType', 'relatedContactDetails', 'relatedContactLocType', 'relatedContactPhoneType', 'relatedContactImProvider', 'relatedContactWebsiteType'); foreach ($relProperties as $relProperty) { $this->set($relProperty, ${$relProperty}); } // store mapping Id to display it in the preview page $this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params)); //Updating Mapping Records if (!empty($params['updateMapping'])) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $mappingFields = new CRM_Core_DAO_MappingField(); $mappingFields->mapping_id = $params['mappingId']; $mappingFields->find(); $mappingFieldsId = array(); while ($mappingFields->fetch()) { if ($mappingFields->id) { $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id; } } for ($i = 0; $i < $this->_columnCount; $i++) { $updateMappingFields = new CRM_Core_DAO_MappingField(); $updateMappingFields->id = CRM_Utils_Array::value($i, $mappingFieldsId); $updateMappingFields->mapping_id = $params['mappingId']; $updateMappingFields->column_number = $i; $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3); $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL; $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL; $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL; if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $updateMappingFields->relationship_type_id = $id; $updateMappingFields->relationship_direction = "{$first}_{$second}"; $updateMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1])); // get phoneType id and provider id separately // before updating mappingFields of phone and IM for related contact, CRM-3140 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'url') { $updateMappingFields->website_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } else { if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') { $updateMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL; } elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') { $updateMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL; } $updateMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } } else { $updateMappingFields->name = $mapper[$i]; $updateMappingFields->relationship_type_id = 'NULL'; $updateMappingFields->relationship_type_direction = 'NULL'; // to store phoneType id and provider id separately // before updating mappingFields for phone and IM, CRM-3140 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'url') { $updateMappingFields->website_type_id = isset($mapperKeys[$i][1]) ? $mapperKeys[$i][1] : NULL; } else { if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') { $updateMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') { $updateMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } $location = array_keys($locationTypes, $locations[$i]); $updateMappingFields->location_type_id = isset($location) && isset($location[0]) ? $location[0] : NULL; } } $updateMappingFields->save(); } } //Saving Mapping Details and Records if (!empty($params['saveMapping'])) { $mappingParams = array('name' => $params['saveMappingName'], 'description' => $params['saveMappingDesc'], 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type', 'Import Contact', 'name')); $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $contactType = $this->get('contactType'); switch ($contactType) { case CRM_Import_Parser::CONTACT_INDIVIDUAL: $cType = 'Individual'; break; case CRM_Import_Parser::CONTACT_HOUSEHOLD: $cType = 'Household'; break; case CRM_Import_Parser::CONTACT_ORGANIZATION: $cType = 'Organization'; } for ($i = 0; $i < $this->_columnCount; $i++) { $saveMappingFields = new CRM_Core_DAO_MappingField(); $saveMappingFields->mapping_id = $saveMapping->id; $saveMappingFields->contact_type = $cType; $saveMappingFields->column_number = $i; $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3); $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL; $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL; $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL; if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $saveMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1])); $saveMappingFields->relationship_type_id = $id; $saveMappingFields->relationship_direction = "{$first}_{$second}"; // to get phoneType id and provider id separately // before saving mappingFields of phone and IM for related contact, CRM-3140 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'url') { $saveMappingFields->website_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } else { if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') { $saveMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL; } elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') { $saveMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL; } $saveMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } } else { $saveMappingFields->name = $mapper[$i]; $location_id = array_keys($locationTypes, $locations[$i]); // to get phoneType id and provider id separately // before saving mappingFields of phone and IM, CRM-3140 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'url') { $saveMappingFields->website_type_id = isset($mapperKeys[$i][1]) ? $mapperKeys[$i][1] : NULL; } else { if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') { $saveMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') { $saveMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL; } $saveMappingFields->location_type_id = isset($location_id[0]) ? $location_id[0] : NULL; } $saveMappingFields->relationship_type_id = NULL; } $saveMappingFields->save(); } $this->set('savedMapping', $saveMappingFields->mapping_id); } $parser = new CRM_Contact_Import_Parser_Contact($mapperKeysMain, $mapperLocType, $mapperPhoneType, $mapperImProvider, $related, $relatedContactType, $relatedContactDetails, $relatedContactLocType, $relatedContactPhoneType, $relatedContactImProvider, $mapperWebsiteType, $relatedContactWebsiteType); $primaryKeyName = $this->get('primaryKeyName'); $statusFieldName = $this->get('statusFieldName'); $parser->run($this->_importTableName, $mapper, CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType'), $primaryKeyName, $statusFieldName, $this->_onDuplicate, NULL, NULL, FALSE, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'), $this->get('dedupe')); // add all the necessary variables to the form $parser->set($this); }
/** * Handle the values in import mode. * * @param int $onDuplicate * The code for what action to take on duplicates. * @param array $values * The array of values belonging to this line. * * @return bool * the result of this processing */ public function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $formatted = array('version' => 3); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; foreach ($params as $key => $val) { if ($val) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } if ($key == 'participant_register_date') { CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date'); $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']); } } } if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) { if (!empty($params['event_id'])) { $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id'); } else { $eventTitle = $params['event_title']; $qParams = array(); $dao = new CRM_Core_DAO(); $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams); } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $indieFields = CRM_Event_BAO_Participant::import(); } $formatValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $formatValues[$key] = $field; } $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE); if ($formatError) { array_unshift($values, $formatError['error_message']); return CRM_Import_Parser::ERROR; } if (!CRM_Utils_Rule::integer($formatted['event_id'])) { array_unshift($values, ts('Invalid value for Event ID')); return CRM_Import_Parser::ERROR; } if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant'); } else { if ($formatValues['participant_id']) { $dao = new CRM_Event_BAO_Participant(); $dao->id = $formatValues['participant_id']; $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant'); if ($dao->find(TRUE)) { $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID')); $participantValues = array(); //@todo calling api functions directly is not supported $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE); if ($newParticipant['error_message']) { array_unshift($values, $newParticipant['error_message']); return CRM_Import_Parser::ERROR; } $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids); if (!empty($formatted['fee_level'])) { $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id); CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams); } $this->_newParticipant[] = $newParticipant->id; return CRM_Import_Parser::VALID; } else { array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $formatValues['version'] = 3; $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) >= 1) { foreach ($matchedIDs as $contactId) { $formatted['contact_id'] = $contactId; $formatted['version'] = 3; $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate); } } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = ''; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (!empty($params['external_identifier'])) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (!empty($formatValues['external_identifier'])) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate); } if (is_array($newParticipant) && civicrm_error($newParticipant)) { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { $contactID = CRM_Utils_Array::value('contactID', $newParticipant); $participantID = CRM_Utils_Array::value('participantID', $newParticipant); $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE); if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) { array_unshift($values, $url); return CRM_Import_Parser::DUPLICATE; } elseif ($newParticipant['error_message']) { array_unshift($values, $newParticipant['error_message']); return CRM_Import_Parser::ERROR; } return CRM_Import_Parser::ERROR; } } if (!(is_array($newParticipant) && civicrm_error($newParticipant))) { $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant); } return CRM_Import_Parser::VALID; }
/** * Handle the values in import mode. * * @param int $onDuplicate * The code for what action to take on duplicates. * @param array $values * The array of values belonging to this line. * * @return bool * the result of this processing */ public function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $formatted = array('version' => 3); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; //for date-Formats $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution'; $customFields = CRM_Core_BAO_CustomField::getFields($customDataType); //CRM-10994 if (isset($params['total_amount']) && $params['total_amount'] == 0) { $params['total_amount'] = '0.00'; } foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType); break; case 'pledge_payment': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $tempIndieFields = CRM_Contribute_DAO_Contribution::import(); $indieFields = $tempIndieFields; } $paramValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $paramValues[$key] = $field; } //import contribution record according to select contact type if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) { $paramValues['contact_type'] = $this->_contactType; } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($params['soft_credit'])) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($paramValues['pledge_payment'])) { $paramValues['contact_type'] = $this->_contactType; } //need to pass $onDuplicate to check import mode. if (!empty($paramValues['pledge_payment'])) { $paramValues['onDuplicate'] = $onDuplicate; } require_once 'CRM/Utils/DeprecatedUtils.php'; $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate); if ($formatError) { array_unshift($values, $formatError['error_message']); if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') { return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR; } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') { return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR; } return CRM_Import_Parser::ERROR; } if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution'); } else { //fix for CRM-2219 - Update Contribution // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) { $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues)); $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds); if ($ids['contribution']) { $formatted['id'] = $ids['contribution']; $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatted['id'], 'Contribution'); //process note if (!empty($paramValues['note'])) { $noteID = array(); $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id'); $daoNote = new CRM_Core_BAO_Note(); $daoNote->entity_table = 'civicrm_contribution'; $daoNote->entity_id = $ids['contribution']; if ($daoNote->find(TRUE)) { $noteID['id'] = $daoNote->id; } $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID); CRM_Core_BAO_Note::add($noteParams, $noteID); unset($formatted['note']); } //need to check existing soft credit contribution, CRM-3968 if (!empty($formatted['soft_credit'])) { $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']); //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']); if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) { foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) { if (!empty($existingSoftCreditValues['soft_credit_id'])) { $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } } } } $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids); $this->_newContributions[] = $newContribution->id; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } else { $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID'); foreach ($dupeIds as $k => $v) { if ($v) { $errorMsg[] = "{$labels[$k]} {$v}"; } } $errorMsg = implode(' AND ', $errorMsg); array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } if ($this->_contactIdIndex < 0) { // set the contact type if its not set if (!isset($paramValues['contact_type'])) { $paramValues['contact_type'] = $this->_contactType; } $paramValues['version'] = 3; //retrieve contact id using contact dedupe rule require_once 'CRM/Utils/DeprecatedUtils.php'; $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; $newContribution = civicrm_api('contribution', 'create', $formatted); if (civicrm_error($newContribution)) { if (is_array($newContribution['error_message'])) { array_unshift($values, $newContribution['error_message']['message']); if ($newContribution['error_message']['params'][0]) { return CRM_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_Import_Parser::ERROR; } } $this->_newContributions[] = $newContribution['id']; $formatted['contribution_id'] = $newContribution['id']; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = NULL; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (!empty($params['external_identifier'])) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (!empty($paramValues['external_identifier'])) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $paramValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } $newContribution = civicrm_api('contribution', 'create', $formatted); if (civicrm_error($newContribution)) { if (is_array($newContribution['error_message'])) { array_unshift($values, $newContribution['error_message']['message']); if ($newContribution['error_message']['params'][0]) { return CRM_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_Import_Parser::ERROR; } } $this->_newContributions[] = $newContribution['id']; $formatted['contribution_id'] = $newContribution['id']; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } }
/** * handle the values in import mode * * @param int $onDuplicate the code for what action to take on duplicates * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $activityLabel = array_search('activity_label', $this->_mapperKeys); if ($activityLabel) { $params = array_merge($params, array('activity_label' => $values[$activityLabel])); } //for date-Formats $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); if (!isset($params['source_contact_id'])) { $params['source_contact_id'] = $session->get('userID'); } $formatted = array(); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); foreach ($params as $key => $val) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($key == 'activity_date_time' && $val) { $params[$key] = CRM_Utils_Date::formatDate($val, $dateType); } elseif ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key); } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } elseif ($key == 'activity_subject') { $params['subject'] = $val; } } //date-Format part ends require_once 'CRM/Utils/DeprecatedUtils.php'; $formatError = _civicrm_api3_deprecated_activity_formatted_param($params, $params, TRUE); if ($formatError) { array_unshift($values, $formatError['error_message']); return CRM_Import_Parser::ERROR; } $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, CRM_Core_DAO::$_nullObject, NULL, 'Activity'); if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule. //since we are support only individual's activity import. $params['contact_type'] = 'Individual'; $params['version'] = 3; $error = _civicrm_api3_deprecated_duplicate_formatted_contact($params); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $params['target_contact_id'] = $cid; $params['version'] = 3; $newActivity = civicrm_api('activity', 'create', $params); if (CRM_Utils_Array::value('is_error', $newActivity)) { array_unshift($values, $newActivity['error_message']); return CRM_Import_Parser::ERROR; } $this->_newActivity[] = $newActivity['id']; return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => 'Individual', 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = NULL; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (CRM_Utils_Array::value('external_identifier', $params)) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (CRM_Utils_Array::value('external_identifier', $params)) { $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier'); if (CRM_Utils_Array::value('target_contact_id', $params) && $params['target_contact_id'] != $targetContactId) { array_unshift($values, 'Mismatch of External identifier :' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']); return CRM_Import_Parser::ERROR; } elseif ($targetContactId) { $params['target_contact_id'] = $targetContactId; } else { array_unshift($values, 'No Matching Contact for External identifier :' . $params['external_identifier']); return CRM_Import_Parser::ERROR; } } $params['version'] = 3; $newActivity = civicrm_api('activity', 'create', $params); if (CRM_Utils_Array::value('is_error', $newActivity)) { array_unshift($values, $newActivity['error_message']); return CRM_Import_Parser::ERROR; } $this->_newActivity[] = $newActivity['id']; return CRM_Import_Parser::VALID; } }
/** * Run the import parser. * * @param array $originalValues * * @param int $onDuplicateAction * @param int $expectedResult */ protected function runImport($originalValues, $onDuplicateAction, $expectedResult) { $fields = array_keys($originalValues); $values = array_values($originalValues); $parser = new CRM_Contact_Import_Parser_Contact($fields); $parser->_contactType = 'Individual'; $parser->_onDuplicate = $onDuplicateAction; $parser->init(); $this->assertEquals($expectedResult, $parser->import($onDuplicateAction, $values)); }
/** * Handle the values in import mode. * * @param int $onDuplicate * The code for what action to take on duplicates. * @param array $values * The array of values belonging to this line. * * @return bool * the result of this processing */ public function import($onDuplicate, &$values) { $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { $importRecordParams = array($statusFieldName => 'INVALID', "{$statusFieldName}Msg" => "Invalid (Error Code: {$response})"); return $response; } $this->_updateWithId = FALSE; $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE); $params = $this->getActiveFieldParams(); $contactType = $this->_contactType ? $this->_contactType : 'Organization'; $formatted = array('contact_type' => $contactType); $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $formatted['id'] = $this->_params['contact_id']; $setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields)); CRM_Contact_Import_Parser_Contact::formatCommonData($this->_params, $formatted, $formatted); foreach ($formatted['custom'] as $key => $val) { $this->_params['custom_' . $key] = $val[-1]['value']; } $this->_params['skipRecentView'] = TRUE; $this->_params['check_permissions'] = TRUE; $this->_params['entity_id'] = $formatted['id']; try { civicrm_api3('custom_value', 'create', $this->_params); } catch (CiviCRM_API3_Exception $e) { $error = $e->getMessage(); array_unshift($values, $error); return CRM_Import_Parser::ERROR; } }