/** * function to check if an error is actually a duplicate contact error * * @param array $error (array of) valid Error values * * @return true if error is duplicate contact error, false otherwise * * @access public */ function civicrm_duplicate($error) { if (is_array($error) && civicrm_error($error)) { $code = $error['error_message']['code']; if ($code == CRM_Core_Error::DUPLICATE_CONTACT) { return true; } } return false; }
/** * Close any pending transactions */ function onApiRespond(\Civi\API\Event\RespondEvent $event) { $apiRequest = $event->getApiRequest(); if (isset($this->transactions[$apiRequest['id']])) { if (civicrm_error($event->getResponse())) { $this->transactions[$apiRequest['id']]->rollback(); } unset($this->transactions[$apiRequest['id']]); } }
/** * ContributionRecur.AmendDDAmount API * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_contribution_recur_amendddamount($params) { if (array_key_exists('contact_id', $params) && array_key_exists('amount', $params) && array_key_exists('contribution_recur_id', $params)) { $iContactId = $params['contact_id']; $iContributionRecurId = $params['contribution_recur_id']; $iAmount = $params['amount']; $iContributionPageId = null; $iRelatedContactId = null; $iOnBehalfDupeAlert = null; $aContribParam['contactID'] = $iContactId; $aContribParam['contributionRecurID'] = $iContributionRecurId; $aContribParam['contributionPageID'] = $iContributionPageId; $aContribParam['relatedContactID'] = $iRelatedContactID; $aContribParam['onBehalfDupeAlert'] = $iOnBehalfDupeAlert; $aParams = array('version' => '3', 'sequential' => '1', 'contact_id' => $iContactId); $aResult = civicrm_api('Membership', 'getsingle', $aParams); if (civicrm_error($aResult)) { $sMsg = "Error locating Membership record for contact id {$iContactId}"; CRM_Core_Error::debug_log_message($sMsg); return civicrm_api3_create_error($sMsg); } $aContribParam['membershipID'] = $aResult['membership_id']; $aParams = array('version' => '3', 'sequential' => '1', 'contribution_recur_id' => $iContributionRecurId); $aResult = civicrm_api('Contribution', 'getsingle', $aParams); if (civicrm_error($aResult)) { $sMsg = "Error locating Contribution record for contribution_recur_id {$iContributionRecurId}"; CRM_Core_Error::debug_log_message($sMsg); return civicrm_api3_create_error($sMsg); } $aContribParam['contributionID'] = $aResult['id']; $SmartDebitIPN = new CRM_Core_Payment_SmartDebitIPN(); $oResult = $SmartDebitIPN->main('contribute', $aContribParam); if ($oResult === false) { $sMsg = "Error when changing DD Amount using Smart Debit."; CRM_Core_Error::debug_log_message($sMsg); return civicrm_api3_create_error($sMsg); } $aParams = array('version' => '3', 'sequential' => '1', 'id' => $iContributionRecurId, 'amount' => $iAmount); $aResult = civicrm_api('ContributionRecur', 'update', $aParams); if (civicrm_error($aResult)) { $sMsg = "Error when updating the Amount in ContributionRecur."; CRM_Core_Error::debug_log_message($sMsg); return civicrm_api3_create_error($sMsg); } return civicrm_api3_create_success(); } else { throw new API_Exception('Missing Mandatory parameters: contact_id, contribution_id, and contribution_recur_id'); } }
function postProcess() { $values = $this->exportValues(); $branchId = $values['pcp_branch_contact']; if ($branchId && $this->get('page_id')) { // $branchCfId = CRM_Pcpteams_Utils::getBranchorPartnerCustomFieldId(); $params = array('version' => 3, 'entity_id' => $this->get('page_id'), "org_id" => $branchId); $result = civicrm_api3('pcpteams', 'customcreate', $params); if (!civicrm_error($result)) { $branchName = CRM_Contact_BAO_Contact::displayName($branchId); // Group Join: create activity $actParams = array('target_contact_id' => $branchId); CRM_Pcpteams_Utils::createPcpActivity($actParams, CRM_Pcpteams_Constant::C_AT_GROUP_JOIN); CRM_Core_Session::setStatus(ts("Successfully added to the branch {$branchName}"), '', 'success'); } } }
/** * Add or update a relationship * * @param array $params (reference ) input parameters * * @return array (reference) id of created or updated record * @static void * @access public */ function civicrm_relationship_create(&$params) { _civicrm_initialize(); if (empty($params)) { return civicrm_create_error('No input parameter present'); } if (!is_array($params)) { return civicrm_create_error(ts('Input parameter is not an array')); } if (!isset($params['contact_id_a']) && !isset($params['contact_id_b']) && !isset($params['relationship_type_id'])) { return civicrm_create_error(ts('Missing required parameters')); } $values = array(); require_once 'CRM/Contact/BAO/Relationship.php'; $error = _civicrm_relationship_format_params($params, $values); if (civicrm_error($error)) { return $error; } $ids = array(); require_once 'CRM/Utils/Array.php'; if (CRM_Utils_Array::value('id', $params)) { $ids['relationship'] = $params['id']; $ids['contactTarget'] = $params['contact_id_b']; } $values['relationship_type_id'] = $params['relationship_type_id'] . '_a_b'; $values['contact_check'] = array($params['contact_id_b'] => $params['contact_id_b']); $ids['contact'] = $params['contact_id_a']; $relationshipBAO = CRM_Contact_BAO_Relationship::create($values, $ids); if (is_a($relationshipBAO, 'CRM_Core_Error')) { return civicrm_create_error("Relationship can not be created"); } else { if ($relationshipBAO[1]) { return civicrm_create_error("Relationship is not valid"); } else { if ($relationshipBAO[2]) { return civicrm_create_error("Relationship already exist"); } } } return civicrm_create_success(array('id' => implode(",", $relationshipBAO[4]))); }
/** * Create an additional location for an existing contact * * @param array $params input properties * * @return array the created location's params * * @access public */ function civicrm_location_add(&$params) { _civicrm_initialize(); $error = _civicrm_location_check_params($params); if (civicrm_error($error)) { return $error; } $locationTypeId = CRM_Utils_Array::value('location_type_id', $params); if (!$locationTypeId && '3.0' != CRM_Utils_Array::value('version', $params)) { require_once 'CRM/Core/DAO/LocationType.php'; $locationTypeDAO =& new CRM_Core_DAO_LocationType(); $locationTypeDAO->name = $params['location_type']; $locationTypeDAO->find(true); $locationTypeId = $locationTypeDAO->id; if (!isset($locationTypeId)) { return civicrm_create_error(ts('$location_type is not valid one')); } } $location =& _civicrm_location_add($params, $locationTypeId); return $location; }
function postProcess() { $values = $this->exportValues(); $tributeId = $values['pcp_tribute_contact']; if ($tributeId && $this->_tributeReason) { // $tributeCfId = CRM_Pcpteams_Utils::getPcpTypeCustomFieldId(); // $tributeContactCfId = CRM_Pcpteams_Utils::getPcpTypeContactCustomFieldId(); $selectedReason = CRM_Core_OptionGroup::getValue(CRM_Pcpteams_Constant::C_PCP_TYPE, $this->_tributeReason, 'name'); $tributeContatparams = array('version' => 3, 'entity_id' => $this->get('page_id'), "tribute" => $selectedReason, "tribute_contact_id" => $tributeId); $result = civicrm_api3('pcpteams', 'customcreate', $tributeContatparams); if (!civicrm_error($result)) { $tributeName = CRM_Contact_BAO_Contact::displayName($tributeId); // Tribute Join: create activity $actParams = array('target_contact_id' => $tributeId, 'reason' => $this->_tributeReason); CRM_Pcpteams_Utils::createPcpActivity($actParams, CRM_Pcpteams_Constant::C_AT_TRIBUTE_JOIN); CRM_Core_Session::setStatus(ts("Successfully added to {$this->_tributeReason} of {$tributeName}"), '', 'success'); } } //FIXME: need to discuss with DS, to redirect the after completed the form entries CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/pcp/page', 'reset=1&id=' . $this->get('page_id'))); }
/** * Create an additional location for an existing contact * * @param array $params input properties * * @return array the created location's params * * @access public */ function civicrm_location_add(&$params) { _civicrm_initialize(); $error = _civicrm_location_check_params($params); if (civicrm_error($error)) { return $error; } $locationTypeId = CRM_Utils_Array::value('location_type_id', $params); if (!$locationTypeId && '2.0' == CRM_Utils_Array::value('location_format', $params)) { require_once 'CRM/Core/DAO/LocationType.php'; $locationTypeDAO = new CRM_Core_DAO_LocationType(); $locationTypeDAO->name = $params['location_type']; $locationTypeDAO->find(TRUE); $locationTypeId = $locationTypeDAO->id; CRM_Core_PseudoConstant::flush('locationType'); if (!isset($locationTypeId)) { return civicrm_create_error(ts('$location_type is not valid one')); } } $location =& _civicrm_location_add($params, $locationTypeId); return $location; }
static function updateCiviGroup(&$params, $op, $groupType = NULL) { $abort = false; $params['version'] = 3; $params['id'] = CRM_Bridge_OG_Utils::groupID($params['source'], $params['title'], $abort); if ($op == 'add') { if ($groupType) { $params['group_type'] = $groupType; } $group = civicrm_api('group', 'create', $params); if (!civicrm_error($group)) { $params['group_id'] = $group['id']; } } else { // do this only if we have a valid id if ($params['id']) { CRM_Contact_BAO_Group::discard($params['id']); $params['group_id'] = $params['id']; } } unset($params['id']); }
/** * Create a Contact Membership * * This API is used for creating a Membership for a contact. * Required parameters : membership_type_id and status_id. * * @param array $params an associative array of name/value property values of civicrm_membership * * @return array of newly created membership property values. * @access public */ function civicrm_membership_contact_create(&$params) { _civicrm_initialize(); $error = _civicrm_membership_check_params($params); if (civicrm_error($error)) { return $error; } $values = array(); $error = _civicrm_membership_format_params($params, $values); if (civicrm_error($error)) { return $error; } $params = array_merge($values, $params); require_once 'CRM/Core/Action.php'; $action = CRM_Core_Action::ADD; // we need user id during add mode $ids = array('userId' => $params['contact_id']); //for edit membership id should be present if (CRM_Utils_Array::value('id', $params)) { $ids = array('membership' => $params['id'], 'userId' => $params['contact_id']); $action = CRM_Core_Action::UPDATE; } //need to pass action to handle related memberships. $params['action'] = $action; require_once 'CRM/Member/BAO/Membership.php'; $membershipBAO = CRM_Member_BAO_Membership::create($params, $ids, true); if (array_key_exists('is_error', $membershipBAO)) { // In case of no valid status for given dates, $membershipBAO // is going to contain 'is_error' => "Error Message" return civicrm_create_error(ts('The membership can not be saved, no valid membership status for given dates')); } $membership = array(); _civicrm_object_to_array($membershipBAO, $membership); $values = array(); $values['id'] = $membership['id']; $values['is_error'] = 0; return $values; }
static function updateCiviGroup(&$params, $op, $groupType = null) { $abort = $op == 'delete' ? true : false; $params['id'] = CRM_Bridge_OG_Utils::groupID($params['source'], $params['title'], $abort); if ($op == 'add') { require_once 'api/v2/Group.php'; if ($groupType) { $params['group_type'] = $groupType; } $group = civicrm_group_add($params); if (!civicrm_error($group)) { $params['group_id'] = $group['result']; } } else { // do this only if we have a valid id if ($params['id']) { require_once 'CRM/Contact/BAO/Group.php'; CRM_Contact_BAO_Group::discard($params['id']); $params['group_id'] = $params['id']; } } unset($params['id']); }
/** * Add or update a relationship * * @param array $params (reference ) input parameters * * @return array (reference) id of created or updated record * @static void * @access public */ function civicrm_relationship_create(&$params) { _civicrm_initialize(); // check params for required fields (add/update) $error = _civicrm_relationship_check_params($params); if (civicrm_error($error)) { return $error; } $values = array(); require_once 'CRM/Contact/BAO/Relationship.php'; $error = _civicrm_relationship_format_params($params, $values); if (civicrm_error($error)) { return $error; } $ids = array(); require_once 'CRM/Utils/Array.php'; if (CRM_Utils_Array::value('id', $params)) { $ids['relationship'] = $params['id']; $ids['contactTarget'] = $params['contact_id_b']; } $values['relationship_type_id'] = $params['relationship_type_id'] . '_a_b'; $values['contact_check'] = array($params['contact_id_b'] => $params['contact_id_b']); $ids['contact'] = $params['contact_id_a']; $relationshipBAO = CRM_Contact_BAO_Relationship::create($values, $ids); if (is_a($relationshipBAO, 'CRM_Core_Error')) { return civicrm_create_error('Relationship can not be created'); } else { if ($relationshipBAO[1]) { return civicrm_create_error('Relationship is not valid'); } else { if ($relationshipBAO[2]) { return civicrm_create_error('Relationship already exists'); } } } return civicrm_create_success(array('id' => implode(',', $relationshipBAO[4]))); }
/** * 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_Member_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); //assign join date equal to start date if join date is not provided if (!$params['join_date'] && $params['membership_start_date']) { $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; foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'join_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage); } break; case 'membership_start_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } break; case 'membership_end_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage); } break; case 'is_override': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID][2] == 'Date') { CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID][2] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } } //date-Format part ends static $indieFields = null; if ($indieFields == null) { require_once 'CRM/Member/DAO/Membership.php'; $tempIndieFields =& CRM_Member_DAO_Membership::import(); $indieFields = $tempIndieFields; } $formatValues = array(); foreach ($params as $key => $field) { if ($field == null || $field === '') { continue; } $formatValues[$key] = $field; } $formatError = _civicrm_membership_formatted_param($formatValues, $formatted, true); if ($formatError) { array_unshift($values, $formatError['error_message']); return CRM_Member_Import_Parser::ERROR; } if ($onDuplicate != CRM_Member_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_Member_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_Member_Import_Parser::ERROR; } if ($formatValues['membership_id']) { require_once 'CRM/Member/BAO/Membership.php'; $dao = new CRM_Member_BAO_Membership(); $dao->id = $formatValues['membership_id']; $dates = array('join_date', 'start_date', 'end_date'); foreach ($dates as $v) { if (!$formatted[$v]) { $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_Member_Import_Parser::ERROR; } else { $this->_newMemberships[] = $newMembership->id; return CRM_Member_Import_Parser::VALID; } } else { array_unshift($values, "Matching Membership record not found for Membership ID " . $formatValues['membership_id'] . ". Row was skipped."); return CRM_Member_Import_Parser::ERROR; } } } //Format dates $startDate = CRM_Utils_Date::customFormat($formatted['start_date'], '%Y-%m-%d'); $endDate = CRM_Utils_Date::customFormat($formatted['end_date'], '%Y-%m-%d'); $joinDate = CRM_Utils_Date::customFormat($formatted['join_date'], '%Y-%m-%d'); if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $error = civicrm_check_contact_dedupe($formatValues); if (civicrm_duplicate($error)) { $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_Member_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; //fix for CRM-1924 require_once 'CRM/Member/BAO/MembershipStatus.php'; require_once 'CRM/Member/BAO/MembershipType.php'; require_once 'CRM/Member/PseudoConstant.php'; $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); if (!$formatted['status_id']) { $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_Member_Import_Parser::ERROR; } else { if ($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_Member_Import_Parser::ERROR; } } } $newMembership = civicrm_contact_membership_create($formatted); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['error_message']); return CRM_Member_Import_Parser::ERROR; } $this->_newMemberships[] = $newMembership['id']; return CRM_Member_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict'); require_once 'CRM/Dedupe/BAO/Rule.php'; $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); 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_Member_Import_Parser::ERROR; } } else { if ($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 identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']); return CRM_Member_Import_Parser::ERROR; } } //to calculate dates require_once 'CRM/Member/BAO/MembershipType.php'; $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; } require_once 'CRM/Member/BAO/MembershipStatus.php'; $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin); if (!$formatted['status_id']) { $formatted['status_id'] = $calcStatus['id']; } else { if (!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_Member_Import_Parser::ERROR; } else { if ($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_Member_Import_Parser::ERROR; } } } } $newMembership = civicrm_contact_membership_create($formatted); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['error_message']); return CRM_Member_Import_Parser::ERROR; } $this->_newMemberships[] = $newMembership['id']; return CRM_Member_Import_Parser::VALID; } }
/** * HRJobContract implementation of the "replace" action. * * Replace the old set of entities (matching some given keys) with a new set of * entities (matching the same keys). * * Note: This will verify that 'values' is present, but it does not directly verify * any other parameters. * * @param string $entity entity name * @param array $params params from civicrm_api, including: * - 'values': an array of records to save * - all other items: keys which identify new/pre-existing records * @return array|int */ function _civicrm_hrjobcontract_api3_replace($entity, $params, $forceRevisionId = null) { $transaction = new CRM_Core_Transaction(); try { if (!is_array($params['values'])) { throw new Exception("Mandatory key(s) missing from params array: values"); } // Extract the keys -- somewhat scary, don't think too hard about it $baseParams = _civicrm_api3_generic_replace_base_params($params); // Lookup pre-existing records $preexisting = civicrm_api($entity, 'get', $baseParams, $params); if (civicrm_error($preexisting)) { $transaction->rollback(); return $preexisting; } // Save the new/updated records $jobcontractRevisionId = null; $creates = array(); foreach ($params['values'] as $replacement) { if (empty($replacement['id']) && empty($replacement['jobcontract_revision_id'])) { $replacement['jobcontract_revision_id'] = $jobcontractRevisionId; } if ($forceRevisionId) { $replacement['jobcontract_revision_id'] = $forceRevisionId; } // Sugar: Don't force clients to duplicate the 'key' data $replacement = array_merge($baseParams, $replacement); //$action = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create'; $action = 'create'; $create = civicrm_api($entity, $action, $replacement); if (civicrm_error($create)) { $transaction->rollback(); return $create; } foreach ($create['values'] as $entity_id => $entity_value) { $creates[$entity_id] = $entity_value; } $entityData = CRM_Utils_Array::first($create['values']); $jobcontractRevisionId = $entityData['jobcontract_revision_id']; } // Remove stale records $staleIDs = array_diff(array_keys($preexisting['values']), array_keys($creates)); foreach ($staleIDs as $staleID) { $delete = civicrm_api($entity, 'delete', array('version' => $params['version'], 'id' => $staleID)); if (civicrm_error($delete)) { $transaction->rollback(); return $delete; } } return civicrm_api3_create_success($creates, $params); } catch (PEAR_Exception $e) { $transaction->rollback(); return civicrm_api3_create_error($e->getMessage()); } catch (Exception $e) { $transaction->rollback(); return civicrm_api3_create_error($e->getMessage()); } }
/** * Register a subscription event. Create a new contact if one does not * already exist. * * @param int $group_id * The group id to subscribe to. * @param string $email * The email address of the (new) contact. * @param int $contactId * Currently used during event registration/contribution. * Specifically to avoid linking group to wrong duplicate contact * during event registration. * @param string $context * * @return int|null * $se_id The id of the subscription event, null on failure */ public static function &subscribe($group_id, $email, $contactId = NULL, $context = NULL) { // CRM-1797 - allow subscription only to public groups $params = array('id' => (int) $group_id); $defaults = array(); $contact_id = NULL; $success = NULL; $bao = CRM_Contact_BAO_Group::retrieve($params, $defaults); if ($bao && substr($bao->visibility, 0, 6) != 'Public' && $context != 'profile') { return $success; } $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; $email = $strtolower($email); // process the query only if no contactId if ($contactId) { $contact_id = $contactId; } else { /* First, find out if the contact already exists */ $query = "\n SELECT DISTINCT contact_a.id as contact_id\n FROM civicrm_contact contact_a\nLEFT JOIN civicrm_email ON contact_a.id = civicrm_email.contact_id\n WHERE civicrm_email.email = %1 AND contact_a.is_deleted = 0"; $params = array(1 => array($email, 'String')); $dao = CRM_Core_DAO::executeQuery($query, $params); $id = array(); // lets just use the first contact id we got if ($dao->fetch()) { $contact_id = $dao->contact_id; } $dao->free(); } $transaction = new CRM_Core_Transaction(); if (!$contact_id) { require_once 'CRM/Utils/DeprecatedUtils.php'; /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual', 'version' => 3); $locationType = CRM_Core_BAO_LocationType::getDefault(); $value = array('email' => $email, 'location_type_id' => $locationType->id); _civicrm_api3_deprecated_add_formatted_param($value, $formatted); $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP; $formatted['fixAddress'] = TRUE; require_once 'api/api.php'; $contact = civicrm_api('contact', 'create', $formatted); if (civicrm_error($contact)) { return $success; } $contact_id = $contact['id']; } elseif (!is_numeric($contact_id) && (int) $contact_id > 0) { // make sure contact_id is numeric return $success; } /* Get the primary email id from the contact to use as a hash input */ $dao = new CRM_Core_DAO(); $query = "\nSELECT civicrm_email.id as email_id\n FROM civicrm_email\n WHERE civicrm_email.email = %1\n AND civicrm_email.contact_id = %2"; $params = array(1 => array($email, 'String'), 2 => array($contact_id, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); if (!$dao->fetch()) { CRM_Core_Error::fatal('Please file an issue with the backtrace'); return $success; } $se = new CRM_Mailing_Event_BAO_Subscribe(); $se->group_id = $group_id; $se->contact_id = $contact_id; $se->time_stamp = date('YmdHis'); $se->hash = substr(sha1("{$group_id}:{$contact_id}:{$dao->email_id}:" . time()), 0, 16); $se->save(); $contacts = array($contact_id); CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id); $transaction->commit(); return $se; }
/** * Method for creating contact. */ public function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = NULL, $requiredCheck = TRUE, $dedupeRuleGroupID = NULL) { $dupeCheck = FALSE; $newContact = NULL; if (is_null($contactId) && $onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) { $dupeCheck = (bool) $onDuplicate; } //get the prefix id etc if exists CRM_Contact_BAO_Contact::resolveDefaults($formatted, TRUE); require_once 'CRM/Utils/DeprecatedUtils.php'; //@todo direct call to API function not supported. // setting required check to false, CRM-2839 // plus we do our own required check in import $error = _civicrm_api3_deprecated_contact_check_params($formatted, $dupeCheck, TRUE, FALSE, $dedupeRuleGroupID); if (is_null($error) && civicrm_error(_civicrm_api3_deprecated_validate_formatted_contact($formatted))) { $error = _civicrm_api3_deprecated_validate_formatted_contact($formatted); } $newContact = $error; if (is_null($error)) { if ($contactId) { $this->formatParams($formatted, $onDuplicate, (int) $contactId); } // pass doNotResetCache flag since resetting and rebuilding cache could be expensive. $config = CRM_Core_Config::singleton(); $config->doNotResetCache = 1; $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']); $config->doNotResetCache = 0; $contact = array('contact_id' => $cid); $defaults = array(); $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } //get the id of the contact whose street address is not parsable, CRM-5886 if ($this->_parseStreetAddress && is_object($newContact) && property_exists($newContact, 'address') && $newContact->address) { foreach ($newContact->address as $address) { if (!empty($address['street_address']) && (empty($address['street_number']) || empty($address['street_name']))) { $this->_unparsedStreetAddressContacts[] = array('id' => $newContact->id, 'streetAddress' => $address['street_address']); } } } return $newContact; }
/** * 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; }
/** * method for creating contact * * */ function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = null, $requiredCheck = true) { $dupeCheck = false; $newContact = null; if (is_null($contactId) && $onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) { $dupeCheck = (bool) $onDuplicate; } //get the prefix id etc if exists CRM_Contact_BAO_Contact::resolveDefaults($formatted, true); require_once 'api/v2/Contact.php'; // setting required check to false, CRM-2839 // plus we do our own required check in import $error = civicrm_contact_check_params($formatted, $dupeCheck, true, false); if (is_null($error) && civicrm_error(_civicrm_validate_formatted_contact($formatted))) { $error = _civicrm_validate_formatted_contact($formatted); } $newContact = $error; if (is_null($error)) { if ($contactId) { $this->formatParams($formatted, $onDuplicate, (int) $contactId); } $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, null, null, $formatted['contact_type']); $contact = array('contact_id' => $cid); $defaults = array(); $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } return $newContact; }
/** * 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; } }
/** * Generic implementation of the "replace" action. * * Replace the old set of entities (matching some given keys) with a new set of * entities (matching the same keys). * * Note: This will verify that 'values' is present, but it does not directly verify * any other parameters. * * @param string $entity entity name * @param array $params params from civicrm_api, including: * - 'values': an array of records to save * - all other items: keys which identify new/pre-existing records */ function _civicrm_api3_generic_replace($entity, $params) { require_once 'CRM/Core/Transaction.php'; $tx = new CRM_Core_Transaction(); try { if (!is_array($params['values'])) { throw new Exception("Mandatory key(s) missing from params array: values"); } // Extract the keys -- somewhat scary, don't think too hard about it $baseParams = $params; unset($baseParams['values']); unset($baseParams['sequential']); // Lookup pre-existing records $preexisting = civicrm_api($entity, 'get', $baseParams, $params); if (civicrm_error($preexisting)) { $tx->rollback(); return $preexisting; } // Save the new/updated records $creates = array(); foreach ($params['values'] as $replacement) { // Sugar: Don't force clients to duplicate the 'key' data $replacement = array_merge($baseParams, $replacement); $action = isset($replacement['id']) || isset($replacement[$entity . '_id']) ? 'update' : 'create'; $create = civicrm_api($entity, $action, $replacement); if (civicrm_error($create)) { $tx->rollback(); return $create; } foreach ($create['values'] as $entity_id => $entity_value) { $creates[$entity_id] = $entity_value; } } // Remove stale records $staleIDs = array_diff(array_keys($preexisting['values']), array_keys($creates)); foreach ($staleIDs as $staleID) { $delete = civicrm_api($entity, 'delete', array('version' => $params['version'], 'id' => $staleID)); if (civicrm_error($delete)) { $tx->rollback(); return $delete; } } return civicrm_api3_create_success($creates, $params); } catch (PEAR_Exception $e) { $tx->rollback(); return civicrm_api3_create_error($e->getMessage()); } catch (Exception $e) { $tx->rollback(); return civicrm_api3_create_error($e->getMessage()); } }
/** * Process a transaction and record it against the contact. * * @param array $params * Input parameters. * * @return array * contribution of created or updated record (or a civicrm error) */ function civicrm_api3_contribution_transact($params) { // Set some params specific to payment processing // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with // 'is_error' set // also trxn_id is not saved. // but since there is no test it's not desirable to jump in & make the obvious changes. $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test'; $params['amount'] = $params['total_amount']; if (!isset($params['net_amount'])) { $params['net_amount'] = $params['amount']; } if (!isset($params['invoiceID']) && isset($params['invoice_id'])) { $params['invoiceID'] = $params['invoice_id']; } // Some payment processors expect a unique invoice_id - generate one if not supplied $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE))); $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']); if (civicrm_error($paymentProcessor)) { return $paymentProcessor; } $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor); if (civicrm_error($payment)) { return $payment; } $transaction = $payment->doPayment($params); $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card'; return civicrm_api('Contribution', 'create', $params); }
/** * Create a new forward event, create a new contact if necessary */ static function &forward($job_id, $queue_id, $hash, $forward_email, $fromEmail = null, $comment = null) { $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash); $successfulForward = false; if (!$q) { return $successfulForward; } /* Find the email address/contact, if it exists */ $contact = CRM_Contact_BAO_Contact::getTableName(); $location = CRM_Core_BAO_Location::getTableName(); $email = CRM_Core_BAO_Email::getTableName(); $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName(); $job = CRM_Mailing_BAO_Job::getTableName(); $mailing = CRM_Mailing_BAO_Mailing::getTableName(); $forward = self::getTableName(); $domain =& CRM_Core_BAO_Domain::getDomain(); $dao =& new CRM_Core_Dao(); $dao->query("\n SELECT {$contact}.id as contact_id,\n {$email}.id as email_id,\n {$contact}.do_not_email as do_not_email,\n {$queueTable}.id as queue_id\n FROM ({$email}, {$job} as temp_job)\n INNER JOIN {$contact}\n ON {$email}.contact_id = {$contact}.id\n LEFT JOIN {$queueTable}\n ON {$email}.id = {$queueTable}.email_id\n LEFT JOIN {$job}\n ON {$queueTable}.job_id = {$job}.id\n AND temp_job.mailing_id = {$job}.mailing_id\n WHERE {$queueTable}.job_id = {$job_id}\n AND {$email}.email = '" . CRM_Utils_Type::escape($forward_email, 'String') . "'"); $dao->fetch(); require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); if (isset($dao->queue_id) || $dao->do_not_email == 1) { /* We already sent this mailing to $forward_email, or we should * never email this contact. Give up. */ return $successfulForward; } require_once 'api/v2/Contact.php'; $contact_params = array('email' => $forward_email); $count = civicrm_contact_search_count($contact_params); if ($count == 0) { require_once 'CRM/Core/BAO/LocationType.php'; /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual'); $locationType = CRM_Core_BAO_LocationType::getDefault(); $value = array('email' => $forward_email, 'location_type_id' => $locationType->id); _civicrm_add_formatted_param($value, $formatted); require_once 'CRM/Import/Parser.php'; $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP; $formatted['fixAddress'] = true; $contact =& civicrm_contact_format_create($formatted); if (civicrm_error($contact, CRM_Core_Error)) { return $successfulForward; } $contact_id = $contact['id']; } $email =& new CRM_Core_DAO_Email(); $email->email = $forward_email; $email->find(true); $email_id = $email->id; if (!$contact_id) { $contact_id = $email->contact_id; } /* Create a new queue event */ $queue_params = array('email_id' => $email_id, 'contact_id' => $contact_id, 'job_id' => $job_id); $queue =& CRM_Mailing_Event_BAO_Queue::create($queue_params); $forward =& new CRM_Mailing_Event_BAO_Forward(); $forward->time_stamp = date('YmdHis'); $forward->event_queue_id = $queue_id; $forward->dest_queue_id = $queue->id; $forward->save(); $dao->reset(); $dao->query(" SELECT {$job}.mailing_id as mailing_id \n FROM {$job}\n WHERE {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer')); $dao->fetch(); $mailing_obj =& new CRM_Mailing_BAO_Mailing(); $mailing_obj->id = $dao->mailing_id; $mailing_obj->find(true); $config =& CRM_Core_Config::singleton(); $mailer =& $config->getMailer(); $recipient = null; $attachments = null; $message =& $mailing_obj->compose($job_id, $queue->id, $queue->hash, $queue->contact_id, $forward_email, $recipient, false, null, $attachments, true, $fromEmail); //append comment if added while forwarding. if (count($comment)) { $message->_txtbody = $comment['body_text'] . $message->_txtbody; if (CRM_Utils_Array::value('body_html', $comment)) { $message->_htmlbody = $comment['body_html'] . '<br />---------------Original message---------------------<br />' . $message->_htmlbody; } } $body = $message->get(); $headers = $message->headers(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); $result = null; if (is_object($mailer)) { $result = $mailer->send($recipient, $headers, $body); CRM_Core_Error::setCallback(); } $params = array('event_queue_id' => $queue->id, 'job_id' => $job_id, 'hash' => $queue->hash); if (is_a($result, PEAR_Error)) { /* Register the bounce event */ $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage())); CRM_Mailing_Event_BAO_Bounce::create($params); } else { $successfulForward = true; /* Register the delivery event */ CRM_Mailing_Event_BAO_Delivered::create($params); } $transaction->commit(); return $successfulForward; }
/** * @deprecated - this is part of the import parser not the API & needs to be moved on out * * @param array $params * @param $onDuplicate * * @return array|bool * <type> */ function _civicrm_api3_deprecated_create_participant_formatted($params, $onDuplicate) { require_once 'CRM/Event/Import/Parser.php'; if ($onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) { CRM_Core_Error::reset(); $error = _civicrm_api3_deprecated_participant_check_params($params, TRUE); if (civicrm_error($error)) { return $error; } } require_once "api/v3/Participant.php"; return civicrm_api3_participant_create($params); }
public function assertAPISuccess($apiResult, $prefix = '') { if (!empty($prefix)) { $prefix .= ': '; } $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message']; if (!empty($apiResult['debug_information'])) { $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE); } if (!empty($apiResult['trace'])) { $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE); } $this->assertFalse(civicrm_error($apiResult), $prefix . $errorMessage); //$this->assertEquals(0, $apiResult['is_error']); }
/** * Call the API on the local server * (kind of defeats the point of a webtest - see CRM-11889) */ function webtest_civicrm_api($entity, $action, $params) { if (!isset($params['version'])) { $params['version'] = 3; } $result = civicrm_api($entity, $action, $params); $this->assertTrue(!civicrm_error($result), 'Civicrm api error.'); return $result; }
/** * method for creating contact * * */ function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = null, $requiredCheck = true) { $dupeCheck = false; $newContact = null; if (is_null($contactId) && $onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) { $dupeCheck = (bool) $onDuplicate; } //get the prefix id etc if exists CRM_Contact_BAO_Contact::resolveDefaults($formatted, true); require_once 'api/v2/Contact.php'; // setting required check to false, CRM-2839 // plus we do our own required check in import $error = civicrm_contact_check_params($formatted, $dupeCheck, true, false); if (is_null($error) && civicrm_error(_civicrm_validate_formatted_contact($formatted))) { $error = _civicrm_validate_formatted_contact($formatted); } $newContact = $error; if (is_null($error)) { if ($contactId) { $this->formatParams($formatted, $onDuplicate, (int) $contactId); } // pass doNotResetCache flag since resetting and rebuilding cache could be expensive. $config =& CRM_Core_Config::singleton(); $config->doNotResetCache = 1; $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, null, null, $formatted['contact_type']); $config->doNotResetCache = 0; $contact = array('contact_id' => $cid); $defaults = array(); $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } //get the id of the contact whose street address is not parsable, CRM-5886 if ($this->_parseStreetAddress && $newContact->address) { foreach ($newContact->address as $address) { if ($address['street_address'] && (!CRM_Utils_Array::value('street_number', $address) || !CRM_Utils_Array::value('street_name', $address))) { $this->_unparsedStreetAddressContacts[] = array('id' => $newContact->id, 'streetAddress' => $address['street_address']); } } } return $newContact; }
/** * 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_Event_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $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; foreach ($params as $key => $val) { if ($val) { if ($key == 'participant_register_date') { if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage); } } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_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); } } } } } if (!($params['participant_role_id'] || $params['participant_role'])) { if ($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) { require_once 'CRM/Event/BAO/Participant.php'; $indieFields =& CRM_Event_BAO_Participant::import(); } $formatValues = array(); foreach ($params as $key => $field) { if ($field == null || $field === '') { continue; } $formatValues[$key] = $field; } $formatError = _civicrm_participant_formatted_param($formatValues, $formatted, true); require_once "api/v2/Participant.php"; if ($formatError) { array_unshift($values, $formatError['error_message']); return CRM_Event_Import_Parser::ERROR; } if (!CRM_Utils_Rule::integer($formatted['event_id'])) { array_unshift($values, ts('Invalid value for Event ID')); return CRM_Event_Import_Parser::ERROR; } if ($onDuplicate != CRM_Event_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Participant'); } else { if ($formatValues['participant_id']) { require_once 'CRM/Event/BAO/Participant.php'; $dao = new CRM_Event_BAO_Participant(); $dao->id = $formatValues['participant_id']; $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['participant_id'], 'Participant'); if ($dao->find(true)) { $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID')); $newParticipant = civicrm_participant_check_params($formatted, false); if ($newParticipant['error_message']) { array_unshift($values, $newParticipant['error_message']); return CRM_Event_Import_Parser::ERROR; } $newParticipant =& CRM_Event_BAO_Participant::create($formatted, $ids); $this->_newParticipant[] = $newParticipant->id; return CRM_Event_Import_Parser::VALID; } else { array_unshift($values, "Matching Participant record not found for Participant ID " . $formatValues['participant_id'] . ". Row was skipped."); return CRM_Event_Import_Parser::ERROR; } } } if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $error = civicrm_check_contact_dedupe($formatValues); if (civicrm_duplicate($error)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) >= 1) { foreach ($matchedIDs as $contactId) { $formatted['contact_id'] = $contactId; $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate); } } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict'); require_once 'CRM/Dedupe/BAO/Rule.php'; $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); 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_Event_Import_Parser::ERROR; } } else { if ($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 identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']); return CRM_Event_Import_Parser::ERROR; } } $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate); } if (is_array($newParticipant) && civicrm_error($newParticipant)) { if ($onDuplicate == CRM_Event_Import_Parser::DUPLICATE_SKIP) { $contactID = CRM_Utils_Array::value('contactID', $newParticipant['error_data']); $participantID = CRM_Utils_Array::value('participantID', $newParticipant['error_data']); $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_Event_Import_Parser::DUPLICATE; } else { if ($newParticipant['error_message']) { array_unshift($values, $newParticipant['error_message']); return CRM_Event_Import_Parser::ERROR; } } return CRM_Event_Import_Parser::ERROR; } } if (!(is_array($newParticipant) && civicrm_error($newParticipant))) { $this->_newParticipants[] = $newParticipant['id']; } return CRM_Event_Import_Parser::VALID; }
/** * Form submission of new/edit contact is processed. */ public function postProcess() { $queue_id = $this->get('queue_id'); $job_id = $this->get('job_id'); $hash = $this->get('hash'); $timeStamp = date('YmdHis'); $formValues = $this->controller->exportValues($this->_name); $params = array(); $params['body_text'] = $formValues['forward_comment']; $html_comment = $formValues['html_comment']; $params['body_html'] = str_replace('%7B', '{', str_replace('%7D', '}', $html_comment)); $emails = array(); for ($i = 0; $i < 5; $i++) { $email = $this->controller->exportValue($this->_name, "email_{$i}"); if (!empty($email)) { $emails[] = $email; } } $forwarded = NULL; foreach ($emails as $email) { $params = array('version' => 3, 'job_id' => $job_id, 'event_queue_id' => $queue_id, 'hash' => $hash, 'email' => $email, 'time_stamp' => $timeStamp, 'fromEmail' => $this->_fromEmail, 'params' => $params); $result = civicrm_api('Mailing', 'event_forward', $params); if (!civicrm_error($result)) { $forwarded++; } } $status = ts('Mailing is not forwarded to the given email address.', array('count' => count($emails), 'plural' => 'Mailing is not forwarded to the given email addresses.')); if ($forwarded) { $status = ts('Mailing is forwarded successfully to %count email address.', array('count' => $forwarded, 'plural' => 'Mailing is forwarded successfully to %count email addresses.')); } CRM_Utils_System::setUFMessage($status); // always redirect to front page of url $session = CRM_Core_Session::singleton(); $config = CRM_Core_Config::singleton(); $session->pushUserContext($config->userFrameworkBaseURL); }
/** * @todo Move this to ContactFormat.php * @deprecated */ function civicrm_contact_format_create(&$params) { _civicrm_initialize(); CRM_Core_DAO::freeResult(); // return error if we have no params if (empty($params)) { return civicrm_create_error('Input Parameters empty'); } $error = _civicrm_required_formatted_contact($params); if (civicrm_error($error)) { return $error; } $error = _civicrm_validate_formatted_contact($params); if (civicrm_error($error)) { return $error; } //get the prefix id etc if exists require_once 'CRM/Contact/BAO/Contact.php'; CRM_Contact_BAO_Contact::resolveDefaults($params, TRUE); require_once 'CRM/Import/Parser.php'; if (CRM_Utils_Array::value('onDuplicate', $params) != CRM_Import_Parser::DUPLICATE_NOCHECK) { CRM_Core_Error::reset(); $error = _civicrm_duplicate_formatted_contact($params); if (civicrm_error($error)) { return $error; } } $contact = CRM_Contact_BAO_Contact::create($params, CRM_Utils_Array::value('fixAddress', $params)); _civicrm_object_to_array($contact, $contactArray); return $contactArray; }