First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,60 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Contribute_Import_Controller extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param string $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
// lets get around the time limit issue if possible, CRM-2113
if (!ini_get('safe_mode')) {
set_time_limit(0);
}
$this->_stateMachine = new CRM_Import_StateMachine($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions($config->uploadDir, array('uploadFile'));
}
}

View file

@ -0,0 +1,218 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Contribute_Import_Field {
/**#@+
* @var string
*/
/**
* Name of the field
*/
public $_name;
/**
* Title of the field to be used in display
*/
public $_title;
/**
* Type of field
* @var enum
*/
public $_type;
/**
* Is this field required
* @var boolean
*/
public $_required;
/**
* Data to be carried for use by a derived class
* @var object
*/
public $_payload;
/**
* Regexp to match the CSV header of this column/field
* @var string
*/
public $_headerPattern;
/**
* Regexp to match the pattern of data from various column/fields
* @var string
*/
public $_dataPattern;
/**
* Value of this field
* @var object
*/
public $_value;
/**
* This is soft credit field
* @var string
*/
public $_softCreditField;
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
* @param null $softCreditField
*/
public function __construct($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//', $softCreditField = NULL) {
$this->_name = $name;
$this->_title = $title;
$this->_type = $type;
$this->_headerPattern = $headerPattern;
$this->_dataPattern = $dataPattern;
$this->_softCreditField = $softCreditField;
$this->_value = NULL;
}
public function resetValue() {
$this->_value = NULL;
}
/**
* Set a value.
*
* The value is in string format. Convert the value to the type of this field
* and set the field value with the appropriate type
*
* @param $value
*/
public function setValue($value) {
$this->_value = $value;
}
/**
* Validate a field.
*
* @return bool
*/
public function validate() {
if (CRM_Utils_System::isNull($this->_value)) {
return TRUE;
}
switch ($this->_name) {
case 'contact_id':
// note: we validate existence of the contact in API, upon
// insert (it would be too costly to do a db call here)
return CRM_Utils_Rule::integer($this->_value);
case 'receive_date':
case 'cancel_date':
case 'receipt_date':
case 'thankyou_date':
return CRM_Utils_Rule::date($this->_value);
case 'non_deductible_amount':
case 'total_amount':
case 'fee_amount':
case 'net_amount':
return CRM_Utils_Rule::money($this->_value);
case 'trxn_id':
static $seenTrxnIds = array();
if (in_array($this->_value, $seenTrxnIds)) {
return FALSE;
}
elseif ($this->_value) {
$seenTrxnIds[] = $this->_value;
return TRUE;
}
else {
$this->_value = NULL;
return TRUE;
}
break;
case 'currency':
return CRM_Utils_Rule::currencyCode($this->_value);
case 'financial_type':
static $contributionTypes = NULL;
if (!$contributionTypes) {
$contributionTypes = CRM_Contribute_PseudoConstant::financialType();
}
if (in_array($this->_value, $contributionTypes)) {
return TRUE;
}
else {
return FALSE;
}
break;
case 'payment_instrument':
static $paymentInstruments = NULL;
if (!$paymentInstruments) {
$paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
}
if (in_array($this->_value, $paymentInstruments)) {
return TRUE;
}
else {
return FALSE;
}
break;
default:
break;
}
// check whether that's a valid custom field id
// and if so, check the contents' validity
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) {
static $customFields = NULL;
if (!$customFields) {
$customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
}
if (!array_key_exists($customFieldID, $customFields)) {
return FALSE;
}
return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value);
}
return TRUE;
}
}

View file

@ -0,0 +1,81 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class gets the name of the file to upload
*/
class CRM_Contribute_Import_Form_DataSource extends CRM_Import_Form_DataSource {
const PATH = 'civicrm/contribute/import';
const IMPORT_ENTITY = 'Contribution';
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$duplicateOptions = array();
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Insert new contributions'), CRM_Import_Parser::DUPLICATE_SKIP
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Update existing contributions'), CRM_Import_Parser::DUPLICATE_UPDATE
);
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('Import mode')
);
$this->setDefaults(array('onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP));
$this->addElement('submit', 'loadMapping', ts('Load Mapping'), NULL, array('onclick' => 'checkSelect()'));
$this->addContactTypeSelector();
}
/**
* Process the uploaded file.
*/
public function postProcess() {
$this->storeFormValues(array(
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
));
$this->submitFileForMapping('CRM_Contribute_Import_Parser_Contribution');
}
}

View file

@ -0,0 +1,558 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class gets the name of the file to upload.
*/
class CRM_Contribute_Import_Form_MapField extends CRM_Import_Form_MapField {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_mapperFields = $this->get('fields');
asort($this->_mapperFields);
$this->_columnCount = $this->get('columnCount');
$this->assign('columnCount', $this->_columnCount);
$this->_dataValues = $this->get('dataValues');
$this->assign('dataValues', $this->_dataValues);
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$this->_onDuplicate = $this->get('onDuplicate', isset($onDuplicate) ? $onDuplicate : "");
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
/* if we had a column header to skip, stash it for later */
$this->_columnHeaders = $this->_dataValues[0];
}
else {
$this->assign('rowDisplayCount', 2);
}
$highlightedFields = array('financial_type', 'total_amount');
//CRM-2219 removing other required fields since for updation only
//invoice id or trxn id or contribution id is required.
if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$remove = array('contribution_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
foreach ($remove as $value) {
unset($this->_mapperFields[$value]);
}
//modify field title only for update mode. CRM-3245
foreach (array(
'contribution_id',
'invoice_id',
'trxn_id',
) as $key) {
$this->_mapperFields[$key] .= ' (match to contribution record)';
$highlightedFields[] = $key;
}
}
elseif ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
unset($this->_mapperFields['contribution_id']);
$highlightedFieldsArray = array(
'contribution_contact_id',
'email',
'first_name',
'last_name',
'external_identifier',
);
foreach ($highlightedFieldsArray as $name) {
$highlightedFields[] = $name;
}
}
// modify field title for contribution status
$this->_mapperFields['contribution_status_id'] = ts('Contribution Status');
$this->assign('highlightedFields', $highlightedFields);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
//to save the current mappings
if (!$this->get('savedMapping')) {
$saveDetailsName = ts('Save this field mapping');
$this->applyFilter('saveMappingName', 'trim');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
else {
$savedMapping = $this->get('savedMapping');
list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
$mappingName = $mappingName[1];
$mappingContactType = $mappingContactType[1];
$mappingLocation = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingLocation));
$mappingPhoneType = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingPhoneType));
$mappingRelation = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingRelation));
//mapping is to be loaded from database
$params = array('id' => $savedMapping);
$temp = array();
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$this->assign('loadedMapping', $mappingDetails->name);
$this->set('loadedMapping', $savedMapping);
$getMappingName = new CRM_Core_DAO_Mapping();
$getMappingName->id = $savedMapping;
$getMappingName->mapping_type = 'Import Contributions';
$getMappingName->find();
while ($getMappingName->fetch()) {
$mapperName = $getMappingName->name;
}
$this->assign('savedName', $mapperName);
$this->add('hidden', 'mappingId', $savedMapping);
$this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
$saveDetailsName = ts('Save as a new field mapping');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
$this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
$this->addFormRule(array('CRM_Contribute_Import_Form_MapField', 'formRule'), $this);
//-------- end of saved mapping stuff ---------
$defaults = array();
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
$headerPatterns = $this->get('headerPatterns');
$dataPatterns = $this->get('dataPatterns');
$mapperKeysValues = $this->controller->exportValue($this->_name, 'mapper');
/* Initialize all field usages to false */
foreach ($mapperKeys as $key) {
$this->_fieldUsed[$key] = FALSE;
}
$this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$sel1 = $this->_mapperFields;
if (!$this->get('onDuplicate')) {
unset($sel1['id']);
unset($sel1['contribution_id']);
}
$softCreditFields['contact_id'] = ts('Contact ID');
$softCreditFields['external_identifier'] = ts('External ID');
$softCreditFields['email'] = ts('Email');
$sel2['soft_credit'] = $softCreditFields;
$sel3['soft_credit']['contact_id'] = $sel3['soft_credit']['external_identifier'] = $sel3['soft_credit']['email'] = CRM_Core_OptionGroup::values('soft_credit_type');
$sel4 = NULL;
// end of soft credit section
$js = "<script type='text/javascript'>\n";
$formName = 'document.forms.' . $this->_name;
//used to warn for mismatch column count or mismatch mapping
$warning = 0;
for ($i = 0; $i < $this->_columnCount; $i++) {
$sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
$jsSet = FALSE;
if ($this->get('savedMapping')) {
if (isset($mappingName[$i])) {
if ($mappingName[$i] != ts('- do not import -')) {
$mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
// reusing contact_type field array for soft credit
$softField = isset($mappingContactType[$i]) ? $mappingContactType[$i] : 0;
if (!$softField) {
$js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
}
$js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
$defaults["mapper[$i]"] = array(
CRM_Utils_Array::value(0, $mappingHeader),
($softField) ? $softField : "",
(isset($locationId)) ? $locationId : "",
(isset($phoneType)) ? $phoneType : "",
);
$jsSet = TRUE;
}
else {
$defaults["mapper[$i]"] = array();
}
if (!$jsSet) {
for ($k = 1; $k < 4; $k++) {
$js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
}
}
}
else {
// this load section to help mapping if we ran out of saved columns when doing Load Mapping
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
if ($hasHeaders) {
$defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
}
else {
$defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
}
}
//end of load mapping
}
else {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
if ($hasHeaders) {
// do array search first to see if has mapped key
$columnKey = array_search($this->_columnHeaders[$i], $this->_mapperFields);
if (isset($this->_fieldUsed[$columnKey])) {
$defaults["mapper[$i]"] = $columnKey;
$this->_fieldUsed[$key] = TRUE;
}
else {
// Infer the default from the column names if we have them
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
0,
);
}
}
else {
// Otherwise guess the default from the form of the data
$defaults["mapper[$i]"] = array(
$this->defaultFromData($dataPatterns, $i),
// $defaultLocationType->id
0,
);
}
if (!empty($mapperKeysValues) && $mapperKeysValues[$i][0] == 'soft_credit') {
$js .= "cj('#mapper_" . $i . "_1').val($mapperKeysValues[$i][1]);\n";
$js .= "cj('#mapper_" . $i . "_2').val($mapperKeysValues[$i][2]);\n";
}
}
$sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
}
$js .= "</script>\n";
$this->assign('initHideBoxes', $js);
//set warning if mismatch in more than
if (isset($mappingName)) {
if (($this->_columnCount != count($mappingName))) {
$warning++;
}
}
if ($warning != 0 && $this->get('savedMapping')) {
$session = CRM_Core_Session::singleton();
$session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
}
else {
$session = CRM_Core_Session::singleton();
$session->setStatus(NULL);
}
$this->setDefaults($defaults);
$this->addButtons(array(
array(
'type' => 'back',
'name' => ts('Previous'),
),
array(
'type' => 'next',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @param $files
* @param $self
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
$errors = array();
$fieldMessage = NULL;
$contactORContributionId = $self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE ? 'contribution_id' : 'contribution_contact_id';
if (!array_key_exists('savedMapping', $fields)) {
$importKeys = array();
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
$contactTypeId = $self->get('contactType');
$contactTypes = array(
CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual',
CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household',
CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization',
);
$params = array(
'used' => 'Unsupervised',
'contact_type' => isset($contactTypes[$contactTypeId]) ? $contactTypes[$contactTypeId] : '',
);
list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
$weightSum = 0;
foreach ($importKeys as $key => $val) {
if (array_key_exists($val, $ruleFields)) {
$weightSum += $ruleFields[$val];
}
if ($val == "soft_credit") {
$mapperKey = CRM_Utils_Array::key('soft_credit', $importKeys);
if (empty($fields['mapper'][$mapperKey][1])) {
if (empty($errors['_qf_default'])) {
$errors['_qf_default'] = '';
}
$errors['_qf_default'] .= ts('Missing required fields: Soft Credit') . '<br />';
}
}
}
foreach ($ruleFields as $field => $weight) {
$fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
}
// FIXME: should use the schema titles, not redeclare them
$requiredFields = array(
$contactORContributionId == 'contribution_id' ? 'contribution_id' : 'contribution_contact_id' => $contactORContributionId == 'contribution_id' ? ts('Contribution ID') : ts('Contact ID'),
'total_amount' => ts('Total Amount'),
'financial_type' => ts('Financial Type'),
);
foreach ($requiredFields as $field => $title) {
if (!in_array($field, $importKeys)) {
if (empty($errors['_qf_default'])) {
$errors['_qf_default'] = '';
}
if ($field == $contactORContributionId) {
if (!($weightSum >= $threshold || in_array('external_identifier', $importKeys)) &&
$self->_onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE
) {
$errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
1 => $threshold,
)) . '<br />';
}
elseif ($self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE &&
!(in_array('invoice_id', $importKeys) || in_array('trxn_id', $importKeys) ||
in_array('contribution_id', $importKeys)
)
) {
$errors['_qf_default'] .= ts('Invoice ID or Transaction ID or Contribution ID are required to match to the existing contribution records in Update mode.') . '<br />';
}
}
else {
$errors['_qf_default'] .= ts('Missing required field: %1', array(
1 => $title,
)) . '<br />';
}
}
}
//at least one field should be mapped during update.
if ($self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$atleastOne = FALSE;
foreach ($self->_mapperFields as $key => $field) {
if (in_array($key, $importKeys) &&
!in_array($key, array('doNotImport', 'contribution_id', 'invoice_id', 'trxn_id'))
) {
$atleastOne = TRUE;
break;
}
}
if (!$atleastOne) {
$errors['_qf_default'] .= ts('At least one contribution field needs to be mapped for update during update mode.') . '<br />';
}
}
}
if (!empty($fields['saveMapping'])) {
$nameField = CRM_Utils_Array::value('saveMappingName', $fields);
if (empty($nameField)) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
$mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Contribution', 'name');
if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
$errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
}
}
}
if (!empty($errors)) {
if (!empty($errors['saveMappingName'])) {
$_flag = 1;
$assignError = new CRM_Core_Page();
$assignError->assign('mappingDetailsError', $_flag);
}
if (!empty($errors['_qf_default'])) {
CRM_Core_Session::setStatus($errors['_qf_default'], ts("Error"), "error");
return $errors;
}
}
return TRUE;
}
/**
* Process the mapped fields and map it into the uploaded file preview the file and extract some summary statistics.
*/
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;
}
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$mapper = $mapperKeys = $mapperKeysMain = $mapperSoftCredit = $softCreditFields = $mapperPhoneType = $mapperSoftCreditType = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
$mapperKeysMain[$i] = $mapperKeys[$i][0];
if (isset($mapperKeys[$i][0]) && $mapperKeys[$i][0] == 'soft_credit') {
$mapperSoftCredit[$i] = $mapperKeys[$i][1];
if (strpos($mapperSoftCredit[$i], '_') !== FALSE) {
list($first, $second) = explode('_', $mapperSoftCredit[$i]);
$softCreditFields[$i] = ucwords($first . " " . $second);
}
else {
$softCreditFields[$i] = $mapperSoftCredit[$i];
}
$mapperSoftCreditType[$i] = array(
'value' => isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : '',
'label' => isset($softCreditTypes[$mapperKeys[$i][2]]) ? $softCreditTypes[$mapperKeys[$i][2]] : '',
);
}
else {
$mapperSoftCredit[$i] = $softCreditFields[$i] = $mapperSoftCreditType[$i] = NULL;
}
}
$this->set('mapper', $mapper);
$this->set('softCreditFields', $softCreditFields);
$this->set('mapperSoftCreditType', $mapperSoftCreditType);
// 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'])) {
$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 = $mappingFieldsId[$i];
$updateMappingFields->mapping_id = $params['mappingId'];
$updateMappingFields->column_number = $i;
$updateMappingFields->name = $mapper[$i];
//reuse contact_type field in db to store fields associated with soft credit
$updateMappingFields->contact_type = isset($mapperSoftCredit[$i]) ? $mapperSoftCredit[$i] : 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 Contribution',
'name'
),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
$saveMappingFields = new CRM_Core_DAO_MappingField();
$saveMappingFields->mapping_id = $saveMapping->id;
$saveMappingFields->column_number = $i;
$saveMappingFields->name = $mapper[$i];
//reuse contact_type field in db to store fields associated with soft credit
$saveMappingFields->contact_type = isset($mapperSoftCredit[$i]) ? $mapperSoftCredit[$i] : NULL;
$saveMappingFields->save();
}
$this->set('savedMapping', $saveMappingFields->mapping_id);
}
$parser = new CRM_Contribute_Import_Parser_Contribution($mapperKeysMain, $mapperSoftCredit, $mapperPhoneType);
$parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType')
);
// add all the necessary variables to the form
$parser->set($this);
}
}

View file

@ -0,0 +1,185 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class previews the uploaded file and returns summary statistics.
*/
class CRM_Contribute_Import_Form_Preview extends CRM_Import_Form_Preview {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
//get the data from the session
$dataValues = $this->get('dataValues');
$mapper = $this->get('mapper');
$softCreditFields = $this->get('softCreditFields');
$mapperSoftCreditType = $this->get('mapperSoftCreditType');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$mismatchCount = $this->get('unMatchCount');
//get the mapping name displayed if the mappingId is set
$mappingId = $this->get('loadMappingId');
if ($mappingId) {
$mapDAO = new CRM_Core_DAO_Mapping();
$mapDAO->id = $mappingId;
$mapDAO->find(TRUE);
$this->assign('loadedMapping', $mappingId);
$this->assign('savedName', $mapDAO->name);
}
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
}
else {
$this->assign('rowDisplayCount', 2);
}
if ($invalidRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($conflictRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$properties = array(
'mapper',
'softCreditFields',
'mapperSoftCreditType',
'dataValues',
'columnCount',
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
/**
* Process the mapped fields and map it into the uploaded file preview the file and extract some summary statistics.
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
$mapperSoftCreditType = $this->get('mapperSoftCreditType');
$mapper = $this->controller->exportValue('MapField', 'mapper');
$mapperKeys = array();
$mapperSoftCredit = array();
$mapperPhoneType = array();
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
if (isset($mapper[$key][0]) && $mapper[$key][0] == 'soft_credit' && isset($mapper[$key])) {
$mapperSoftCredit[$key] = isset($mapper[$key][1]) ? $mapper[$key][1] : '';
$mapperSoftCreditType[$key] = $mapperSoftCreditType[$key]['value'];
}
else {
$mapperSoftCredit[$key] = $mapperSoftCreditType[$key] = NULL;
}
}
$parser = new CRM_Contribute_Import_Parser_Contribution($mapperKeys, $mapperSoftCredit, $mapperPhoneType, $mapperSoftCreditType);
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
$header = array();
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
$mapperFields[] = implode(' - ', $header);
}
$parser->run($fileName, $seperator,
$mapperFields,
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$this->get('contactType'),
$onDuplicate
);
// Add all the necessary variables to the form.
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// Check if there is any error occurred.
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
$errorMessage = array();
if (is_array($errors)) {
foreach ($errors as $key => $value) {
$errorMessage[] = $value['message'];
}
$errorFile = $fileName['name'] . '.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_Contribute_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
}
}

View file

@ -0,0 +1,128 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class summarizes the import results.
*/
class CRM_Contribute_Import_Form_Summary extends CRM_Import_Form_Summary {
/**
* Set variables up before form is built.
*/
public function preProcess() {
// set the error message path to display
$this->assign('errorFile', $this->get('errorFile'));
$totalRowCount = $this->get('totalRowCount');
$relatedCount = $this->get('relatedCount');
$totalRowCount += $relatedCount;
$this->set('totalRowCount', $totalRowCount);
$invalidRowCount = $this->get('invalidRowCount');
$invalidSoftCreditRowCount = $this->get('invalidSoftCreditRowCount');
if ($invalidSoftCreditRowCount) {
$urlParams = 'type=' . CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadSoftCreditErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$validSoftCreditRowCount = $this->get('validSoftCreditRowCount');
$invalidPledgePaymentRowCount = $this->get('invalidPledgePaymentRowCount');
if ($invalidPledgePaymentRowCount) {
$urlParams = 'type=' . CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadPledgePaymentErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$validPledgePaymentRowCount = $this->get('validPledgePaymentRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$duplicateRowCount = $this->get('duplicateRowCount');
$onDuplicate = $this->get('onDuplicate');
$mismatchCount = $this->get('unMatchCount');
if ($duplicateRowCount > 0) {
$urlParams = 'type=' . CRM_Import_Parser::DUPLICATE . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadDuplicateRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
elseif ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
else {
$duplicateRowCount = 0;
$this->set('duplicateRowCount', $duplicateRowCount);
}
$this->assign('dupeError', FALSE);
if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$dupeActionString = ts('These records have been updated with the imported data.');
}
elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
$dupeActionString = ts('These records have been filled in with the imported data.');
}
else {
/* Skip by default */
$dupeActionString = ts('These records have not been imported.');
$this->assign('dupeError', TRUE);
/* only subtract dupes from successful import if we're skipping */
$this->set('validRowCount', $totalRowCount - $invalidRowCount -
$conflictRowCount - $duplicateRowCount - $mismatchCount - $invalidSoftCreditRowCount - $invalidPledgePaymentRowCount
);
}
$this->assign('dupeActionString', $dupeActionString);
$properties = array(
'totalRowCount',
'validRowCount',
'invalidRowCount',
'validSoftCreditRowCount',
'invalidSoftCreditRowCount',
'conflictRowCount',
'downloadConflictRecordsUrl',
'downloadErrorRecordsUrl',
'duplicateRowCount',
'downloadDuplicateRecordsUrl',
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
'validPledgePaymentRowCount',
'invalidPledgePaymentRowCount',
'downloadPledgePaymentErrorRecordsUrl',
'downloadSoftCreditErrorRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
}

View file

@ -0,0 +1,662 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
abstract class CRM_Contribute_Import_Parser extends CRM_Import_Parser {
/**
* Contribution-specific result codes
* @see CRM_Import_Parser result code constants
*/
const SOFT_CREDIT = 512, SOFT_CREDIT_ERROR = 1024, PLEDGE_PAYMENT = 2048, PLEDGE_PAYMENT_ERROR = 4096;
protected $_fileName;
/**
* Imported file size
*/
protected $_fileSize;
/**
* Seperator being used
*/
protected $_seperator;
/**
* Total number of lines in file
*/
protected $_lineCount;
/**
* Running total number of valid soft credit rows
*/
protected $_validSoftCreditRowCount;
/**
* Running total number of invalid soft credit rows
*/
protected $_invalidSoftCreditRowCount;
/**
* Running total number of valid pledge payment rows
*/
protected $_validPledgePaymentRowCount;
/**
* Running total number of invalid pledge payment rows
*/
protected $_invalidPledgePaymentRowCount;
/**
* Array of pledge payment error lines, bounded by MAX_ERROR
*/
protected $_pledgePaymentErrors;
/**
* Array of pledge payment error lines, bounded by MAX_ERROR
*/
protected $_softCreditErrors;
/**
* Filename of pledge payment error data
*
* @var string
*/
protected $_pledgePaymentErrorsFileName;
/**
* Filename of soft credit error data
*
* @var string
*/
protected $_softCreditErrorsFileName;
/**
* Whether the file has a column header or not
*
* @var boolean
*/
protected $_haveColumnHeader;
/**
* @param string $fileName
* @param string $seperator
* @param $mapper
* @param bool $skipColumnHeader
* @param int $mode
* @param int $contactType
* @param int $onDuplicate
*
* @return mixed
* @throws Exception
*/
public function run(
$fileName,
$seperator = ',',
&$mapper,
$skipColumnHeader = FALSE,
$mode = self::MODE_PREVIEW,
$contactType = self::CONTACT_INDIVIDUAL,
$onDuplicate = self::DUPLICATE_SKIP
) {
if (!is_array($fileName)) {
CRM_Core_Error::fatal();
}
$fileName = $fileName['name'];
switch ($contactType) {
case self::CONTACT_INDIVIDUAL:
$this->_contactType = 'Individual';
break;
case self::CONTACT_HOUSEHOLD:
$this->_contactType = 'Household';
break;
case self::CONTACT_ORGANIZATION:
$this->_contactType = 'Organization';
}
$this->init();
$this->_haveColumnHeader = $skipColumnHeader;
$this->_seperator = $seperator;
$fd = fopen($fileName, "r");
if (!$fd) {
return FALSE;
}
$this->_lineCount = $this->_warningCount = $this->_validSoftCreditRowCount = $this->_validPledgePaymentRowCount = 0;
$this->_invalidRowCount = $this->_validCount = $this->_invalidSoftCreditRowCount = $this->_invalidPledgePaymentRowCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
$this->_errors = array();
$this->_warnings = array();
$this->_conflicts = array();
$this->_pledgePaymentErrors = array();
$this->_softCreditErrors = array();
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
$this->_rows = array();
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
while (!feof($fd)) {
$this->_lineCount++;
$values = fgetcsv($fd, 8192, $seperator);
if (!$values) {
continue;
}
self::encloseScrub($values);
// skip column header if we're not in mapfield mode
if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
$skipColumnHeader = FALSE;
continue;
}
/* trim whitespace around the values */
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
}
if (CRM_Utils_System::isNull($values)) {
continue;
}
$this->_totalCount++;
if ($mode == self::MODE_MAPFIELD) {
$returnCode = $this->mapField($values);
}
elseif ($mode == self::MODE_PREVIEW) {
$returnCode = $this->preview($values);
}
elseif ($mode == self::MODE_SUMMARY) {
$returnCode = $this->summary($values);
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
}
else {
$returnCode = self::ERROR;
}
// note that a line could be valid but still produce a warning
if ($returnCode == self::VALID) {
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode == self::SOFT_CREDIT) {
$this->_validSoftCreditRowCount++;
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode == self::PLEDGE_PAYMENT) {
$this->_validPledgePaymentRowCount++;
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode == self::WARNING) {
$this->_warningCount++;
if ($this->_warningCount < $this->_maxWarningCount) {
$this->_warningCount[] = $line;
}
}
if ($returnCode == self::ERROR) {
$this->_invalidRowCount++;
if ($this->_invalidRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_errors[] = $values;
}
}
if ($returnCode == self::PLEDGE_PAYMENT_ERROR) {
$this->_invalidPledgePaymentRowCount++;
if ($this->_invalidPledgePaymentRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_pledgePaymentErrors[] = $values;
}
}
if ($returnCode == self::SOFT_CREDIT_ERROR) {
$this->_invalidSoftCreditRowCount++;
if ($this->_invalidSoftCreditRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_softCreditErrors[] = $values;
}
}
if ($returnCode == self::CONFLICT) {
$this->_conflictCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_conflicts[] = $values;
}
if ($returnCode == self::DUPLICATE) {
if ($returnCode == self::MULTIPLE_DUPE) {
/* TODO: multi-dupes should be counted apart from singles
* on non-skip action */
}
$this->_duplicateCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_duplicates[] = $values;
if ($onDuplicate != self::DUPLICATE_SKIP) {
$this->_validCount++;
}
}
// we give the derived class a way of aborting the process
// note that the return code could be multiple code or'ed together
if ($returnCode == self::STOP) {
break;
}
// if we are done processing the maxNumber of lines, break
if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
break;
}
}
fclose($fd);
if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
$customHeaders = $mapper;
$customfields = CRM_Core_BAO_CustomField::getFields('Contribution');
foreach ($customHeaders as $key => $value) {
if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
$customHeaders[$key] = $customfields[$id][0];
}
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_invalidPledgePaymentRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_pledgePaymentErrorsFileName = self::errorFileName(self::PLEDGE_PAYMENT_ERROR);
self::exportCSV($this->_pledgePaymentErrorsFileName, $headers, $this->_pledgePaymentErrors);
}
if ($this->_invalidSoftCreditRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_softCreditErrorsFileName = self::errorFileName(self::SOFT_CREDIT_ERROR);
self::exportCSV($this->_softCreditErrorsFileName, $headers, $this->_softCreditErrors);
}
if ($this->_conflictCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('View Contribution URL'),
),
$customHeaders
);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
}
}
return $this->fini();
}
/**
* Given a list of the importable field keys that the user has selected
* set the active fields array to this list
*
* @param array $fieldKeys mapped array of values
*/
public function setActiveFields($fieldKeys) {
$this->_activeFieldCount = count($fieldKeys);
foreach ($fieldKeys as $key) {
if (empty($this->_fields[$key])) {
$this->_activeFields[] = new CRM_Contribute_Import_Field('', ts('- do not import -'));
}
else {
$this->_activeFields[] = clone($this->_fields[$key]);
}
}
}
/**
* @param array $elements
*/
public function setActiveFieldSoftCredit($elements) {
for ($i = 0; $i < count($elements); $i++) {
$this->_activeFields[$i]->_softCreditField = $elements[$i];
}
}
/**
* @param array $elements
*/
public function setActiveFieldSoftCreditType($elements) {
for ($i = 0; $i < count($elements); $i++) {
$this->_activeFields[$i]->_softCreditType = $elements[$i];
}
}
/**
* Format the field values for input to the api.
*
* @return array
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
$params = array();
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)) {
if (isset($this->_activeFields[$i]->_softCreditField)) {
if (!isset($params[$this->_activeFields[$i]->_name])) {
$params[$this->_activeFields[$i]->_name] = array();
}
$params[$this->_activeFields[$i]->_name][$i][$this->_activeFields[$i]->_softCreditField] = $this->_activeFields[$i]->_value;
if (isset($this->_activeFields[$i]->_softCreditType)) {
$params[$this->_activeFields[$i]->_name][$i]['soft_credit_type_id'] = $this->_activeFields[$i]->_softCreditType;
}
}
if (!isset($params[$this->_activeFields[$i]->_name])) {
if (!isset($this->_activeFields[$i]->_softCreditField)) {
$params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
}
}
}
}
return $params;
}
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
if (empty($name)) {
$this->_fields['doNotImport'] = new CRM_Contribute_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$tempField = CRM_Contact_BAO_Contact::importableFields('All', NULL);
if (!array_key_exists($name, $tempField)) {
$this->_fields[$name] = new CRM_Contribute_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern,
CRM_Utils_Array::value('hasLocationType', $tempField[$name])
);
}
}
}
/**
* Store parser values.
*
* @param CRM_Core_Session $store
*
* @param int $mode
*/
public function set($store, $mode = self::MODE_SUMMARY) {
$store->set('fileSize', $this->_fileSize);
$store->set('lineCount', $this->_lineCount);
$store->set('seperator', $this->_seperator);
$store->set('fields', $this->getSelectValues());
$store->set('fieldTypes', $this->getSelectTypes());
$store->set('headerPatterns', $this->getHeaderPatterns());
$store->set('dataPatterns', $this->getDataPatterns());
$store->set('columnCount', $this->_activeFieldCount);
$store->set('totalRowCount', $this->_totalCount);
$store->set('validRowCount', $this->_validCount);
$store->set('invalidRowCount', $this->_invalidRowCount);
$store->set('invalidSoftCreditRowCount', $this->_invalidSoftCreditRowCount);
$store->set('validSoftCreditRowCount', $this->_validSoftCreditRowCount);
$store->set('invalidPledgePaymentRowCount', $this->_invalidPledgePaymentRowCount);
$store->set('validPledgePaymentRowCount', $this->_validPledgePaymentRowCount);
$store->set('conflictRowCount', $this->_conflictCount);
switch ($this->_contactType) {
case 'Individual':
$store->set('contactType', CRM_Import_Parser::CONTACT_INDIVIDUAL);
break;
case 'Household':
$store->set('contactType', CRM_Import_Parser::CONTACT_HOUSEHOLD);
break;
case 'Organization':
$store->set('contactType', CRM_Import_Parser::CONTACT_ORGANIZATION);
}
if ($this->_invalidRowCount) {
$store->set('errorsFileName', $this->_errorFileName);
}
if ($this->_conflictCount) {
$store->set('conflictsFileName', $this->_conflictFileName);
}
if (isset($this->_rows) && !empty($this->_rows)) {
$store->set('dataValues', $this->_rows);
}
if ($this->_invalidPledgePaymentRowCount) {
$store->set('pledgePaymentErrorsFileName', $this->_pledgePaymentErrorsFileName);
}
if ($this->_invalidSoftCreditRowCount) {
$store->set('softCreditErrorsFileName', $this->_softCreditErrorsFileName);
}
if ($mode == self::MODE_IMPORT) {
$store->set('duplicateRowCount', $this->_duplicateCount);
if ($this->_duplicateCount) {
$store->set('duplicatesFileName', $this->_duplicateFileName);
}
}
}
/**
* Export data to a CSV file.
*
* @param string $fileName
* @param array $header
* @param array $data
*/
public static function exportCSV($fileName, $header, $data) {
$output = array();
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
$header[$key] = "\"$value\"";
}
$config = CRM_Core_Config::singleton();
$output[] = implode($config->fieldSeparator, $header);
foreach ($data as $datum) {
foreach ($datum as $key => $value) {
if (isset($value[0]) && is_array($value)) {
foreach ($value[0] as $k1 => $v1) {
if ($k1 == 'location_type_id') {
continue;
}
$datum[$k1] = $v1;
}
}
else {
$datum[$key] = "\"$value\"";
}
}
$output[] = implode($config->fieldSeparator, $datum);
}
fwrite($fd, implode("\n", $output));
fclose($fd);
}
/**
* Determines the file extension based on error code.
*
* @param int $type
* Error code constant.
*
* @return string
*/
public static function errorFileName($type) {
$fileName = NULL;
if (empty($type)) {
return $fileName;
}
$config = CRM_Core_Config::singleton();
$fileName = $config->uploadDir . "sqlImport";
switch ($type) {
case CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR:
$fileName .= '.softCreditErrors';
break;
case CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR:
$fileName .= '.pledgePaymentErrors';
break;
default:
$fileName = parent::errorFileName($type);
break;
}
return $fileName;
}
/**
* Determines the file name based on error code.
*
* @param int $type
* Error code constant.
*
* @return string
*/
public static function saveFileName($type) {
$fileName = NULL;
if (empty($type)) {
return $fileName;
}
switch ($type) {
case CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR:
$fileName = 'Import_Soft_Credit_Errors.csv';
break;
case CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR:
$fileName = 'Import_Pledge_Payment_Errors.csv';
break;
default:
$fileName = parent::saveFileName($type);
break;
}
return $fileName;
}
}

View file

@ -0,0 +1,611 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Class to parse contribution csv files.
*/
class CRM_Contribute_Import_Parser_Contribution extends CRM_Contribute_Import_Parser {
protected $_mapperKeys;
private $_contactIdIndex;
private $_totalAmountIndex;
private $_contributionTypeIndex;
protected $_mapperSoftCredit;
//protected $_mapperPhoneType;
/**
* Array of successfully imported contribution id's
*
* @array
*/
protected $_newContributions;
/**
* Class constructor.
*
* @param $mapperKeys
* @param null $mapperSoftCredit
* @param null $mapperPhoneType
* @param null $mapperSoftCreditType
*/
public function __construct(&$mapperKeys, $mapperSoftCredit = NULL, $mapperPhoneType = NULL, $mapperSoftCreditType = NULL) {
parent::__construct();
$this->_mapperKeys = &$mapperKeys;
$this->_mapperSoftCredit = &$mapperSoftCredit;
$this->_mapperSoftCreditType = &$mapperSoftCreditType;
}
/**
* The initializer code, called before the processing
*/
public function init() {
$fields = CRM_Contribute_BAO_Contribution::importableFields($this->_contactType, FALSE);
$fields = array_merge($fields,
array(
'soft_credit' => array(
'title' => ts('Soft Credit'),
'softCredit' => TRUE,
'headerPattern' => '/Soft Credit/i',
),
)
);
// add pledge fields only if its is enabled
if (CRM_Core_Permission::access('CiviPledge')) {
$pledgeFields = array(
'pledge_payment' => array(
'title' => ts('Pledge Payment'),
'headerPattern' => '/Pledge Payment/i',
),
'pledge_id' => array(
'title' => ts('Pledge ID'),
'headerPattern' => '/Pledge ID/i',
),
);
$fields = array_merge($fields, $pledgeFields);
}
foreach ($fields as $name => $field) {
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
$field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
$field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
$this->_newContributions = array();
$this->setActiveFields($this->_mapperKeys);
$this->setActiveFieldSoftCredit($this->_mapperSoftCredit);
$this->setActiveFieldSoftCreditType($this->_mapperSoftCreditType);
// FIXME: we should do this in one place together with Form/MapField.php
$this->_contactIdIndex = -1;
$this->_totalAmountIndex = -1;
$this->_contributionTypeIndex = -1;
$index = 0;
foreach ($this->_mapperKeys as $key) {
switch ($key) {
case 'contribution_contact_id':
$this->_contactIdIndex = $index;
break;
case 'total_amount':
$this->_totalAmountIndex = $index;
break;
case 'financial_type':
$this->_contributionTypeIndex = $index;
break;
}
$index++;
}
}
/**
* Handle the values in mapField mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
*/
public function mapField(&$values) {
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in preview mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function preview(&$values) {
return $this->summary($values);
}
/**
* Handle the values in summary mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function summary(&$values) {
$erroneousField = NULL;
$response = $this->setActiveFieldValues($values, $erroneousField);
$params = &$this->getActiveFieldParams();
$errorMessage = NULL;
//for date-Formats
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
foreach ($params as $key => $val) {
if ($val) {
switch ($key) {
case 'receive_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Receive Date', $errorMessage);
}
break;
case 'cancel_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Cancel Date', $errorMessage);
}
break;
case 'receipt_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Receipt date', $errorMessage);
}
break;
case 'thankyou_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Thankyou Date', $errorMessage);
}
break;
}
}
}
//date-Format part ends
$params['contact_type'] = 'Contribution';
//checking error in custom data
CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
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 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'])) {
civicrm_api3('ContributionSoft', 'delete', array(
'id' => $existingSoftCreditValues['soft_credit_id'],
'pcp_id' => NULL,
));
}
}
}
}
$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;
}
$error = $this->checkContactDuplicate($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;
}
}
/**
* Process pledge payments.
*
* @param array $formatted
*
* @return int
*/
public function processPledgePayments(&$formatted) {
if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) {
//get completed status
$completeStatusID = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
//need to update payment record to map contribution_id
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'],
'contribution_id', $formatted['contribution_id']
);
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($formatted['pledge_id'],
array($formatted['pledge_payment_id']),
$completeStatusID,
NULL,
$formatted['total_amount']
);
return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT;
}
}
/**
* Get the array of successfully imported contribution id's
*
* @return array
*/
public function &getImportedContributions() {
return $this->_newContributions;
}
/**
* The initializer code, called before the processing.
*/
public function fini() {
}
}